代码之家  ›  专栏  ›  技术社区  ›  naim5am

如何显示哪些子正则表达式不匹配?

  •  2
  • naim5am  · 技术社区  · 15 年前

    我正在使用正则表达式验证用户输入。以下代码收集可通过themich.groups[标识符]访问的匹配项。如何获取每个组中不匹配的子字符串列表?

    #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( @"(?<time>(\d|\:)+)\s" +
             // ip address = one or more digits or dots followed by  space
             @"(?<ip>(\d|\.)+)\s" +
             // site = one or more characters
             @"(?<site>\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中使用regexs有很好的参考。
    谢谢,谢谢你的帮助。

    1 回复  |  直到 15 年前
        1
  •  2
  •   Ahmad Mageed    15 年前

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

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

    如果你在找一本好书,那么最受欢迎的是杰弗里·弗里德尔的 Mastering Regular Expressions . 最近一本评级为正的书是 Regular Expressions Cookbook .