如何显示哪个子正则表达式无法匹配?

我正在使用正则表达式来validation用户输入。 以下代码收集可与theMatch.Groups [“identifier”]一起访问的匹配项。 如何获得每个组中不匹配的子字符串列表?

#region Using directives using System; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; namespace RegExGroup { class Test { public static void Main( ) { string string1 = "04:03:27 127.0.0.0 comcom.com"; // group time = one or more digits or colons followed by space Regex theReg = new Regex( @"(?(\d|\:)+)\s" + // ip address = one or more digits or dots followed by space @"(?(\d|\.)+)\s" + // site = one or more characters @"(?\S+)" ); // get the collection of matches MatchCollection theMatches = theReg.Matches( string1 ); // iterate through the collection foreach ( Match theMatch in theMatches ) { if ( theMatch.Length != 0 ) { Console.WriteLine( "\ntheMatch: {0}", theMatch.ToString( ) ); Console.WriteLine( "time: {0}", theMatch.Groups["time"] ); Console.WriteLine( "ip: {0}", theMatch.Groups["ip"] ); Console.WriteLine( "site: {0}", theMatch.Groups["site"] ); } } } } } 

所以如果用户输入0xx:03:27 127.0.0.0?.com
我想要输出

  time: 0xx:03:27 site: ?.com 

另外,任何人都有很好的参考资料在C#中使用正则表达式?
谢谢,任何帮助表示感谢。

您是否在询问如何确定哪个特定捕获组无法匹配? 据我所知,一旦比赛失败,您将无法提取此类信息。 如果失败则失败; 不能检索部分匹配尝试信息。 您可以做的是按原样应用整个正则表达式以按所需顺序检查模式。 然后,如果失败,请分别尝试正则表达式的每个部分,并告诉用户哪一个失败(时间,IP,站点)。 在这种情况下,这种方法可能有意义,但可能不适用于所有类型的模式。

关于参考文献,这里有几个链接:

  • .Net Regex资源参考(MSDN论坛,各种各样的链接)
  • http://www.regular-expressions.info/
  • 30分钟正则表达式教程 – 很好的教程,Expresso工具的作者
  • Expresso工具 – 测试你的正则表达式的好工具,有一些样本和上面的教程包括在内。 对于其他工具,请查看上面的MSDN链接。
  • Scott Hanselman的2009工具列表 – 列出了几个正则表达式链接

如果你正在寻找一本好书,那么最受欢迎的是Jeffrey Friedl的Mastering Regular Expressions 。 最近出版的一本评级为正的书是正则表达式食谱 。