正则表达式匹配多个组

时间:2012-12-03 18:16:56

标签: c# regex

我有一个带有正则表达式的字符串示例,我想要匹配:

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

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

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

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

谢谢!

2 个答案:

答案 0 :(得分:4)

因为您在捕获组上有一个量词,所以您只能看到上一次迭代的捕获。幸运的是,.NET(与其他实现不同)提供了一种机制,可以通过the CaptureCollection class所有迭代中检索捕获。来自链接文档:

  

如果量化器应用于捕获组,则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);
  }

答案 1 :(得分:0)

这适用于您当前的字符串。我需要一个更好的例子(更多的字符串等),看看这是否会破坏那些。单词边界(\ b)检查任何非单词字符:

\b[0-9a-fA-F]{2}\b
相关问题