正则表达式匹配多个组

Mar*_*ark 5 c# regex

我有以下我正在尝试匹配的正则表达式字符串示例:

正则表达式: ^\d{3}( [0-9a-fA-F]{2}){3}

要匹配的字符串: 010 00 00 00

我的问题是 - 正则表达式匹配并捕获1组 - 00字符串末尾的最后一组.但是,我希望它最终匹配所有三个00组.为什么这不起作用?当然,括号应该表示它们都是平等匹配的吗?

我知道我可以分别输入三个组,但这只是一个更长的字符串的简短提取,所以这将是一个痛苦.我希望这会提供更优雅的解决方案,但似乎我的理解有点缺乏!

谢谢!

And*_*ong 5

由于捕获组上有量词,因此您只能看到上次迭代的捕获。不过幸运的是,.NET(与其他实现不同)提供了一种通过CaptureCollection 类从所有迭代中检索捕获的机制。从链接的文档中:

如果将量词应用于捕获组,则 CaptureCollection 将为每个捕获的子字符串包含一个 Capture 对象,并且 Group 对象仅提供有关最后捕获的子字符串的信息。

链接文档中提供了示例:

  // Match a sentence with a pattern that has a quantifier that  
  // applies to the entire group.
  pattern = @"(\b\w+\W{1,2})+";
  match = Regex.Match(input, pattern);
  Console.WriteLine("Pattern: " + pattern);
  Console.WriteLine("Match: " + match.Value);
  Console.WriteLine("  Match.Captures: {0}", match.Captures.Count);
  for (int ctr = 0; ctr < match.Captures.Count; ctr++)
     Console.WriteLine("    {0}: '{1}'", ctr, match.Captures[ctr].Value);

  Console.WriteLine("  Match.Groups: {0}", match.Groups.Count);
  for (int groupCtr = 0; groupCtr < match.Groups.Count; groupCtr++)
  {
     Console.WriteLine("    Group {0}: '{1}'", groupCtr, match.Groups[groupCtr].Value);
     Console.WriteLine("    Group({0}).Captures: {1}", 
                       groupCtr, match.Groups[groupCtr].Captures.Count);
     for (int captureCtr = 0; captureCtr < match.Groups[groupCtr].Captures.Count; captureCtr++)
        Console.WriteLine("      Capture {0}: '{1}'", captureCtr, match.Groups[groupCtr].Captures[captureCtr].Value);
  }
Run Code Online (Sandbox Code Playgroud)