c# - 正则表达式匹配多个组

标签 c# regex

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

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

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

我的问题是 - 正则表达式匹配并捕获 1 组 - 字符串末尾的最后一个 00。但是,我希望它在末尾匹配所有三个 00 组。为什么这不起作用?括号里应该是均等匹配的意思吧?

我知道我可以单独输入这三个组,但这只是一个更长字符串的简短摘录,所以这会很痛苦。我希望这会提供一个更优雅的解决方案,但似乎我的理解有些欠缺!

谢谢!

最佳答案

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

If a quantifier is applied to a capturing group, the CaptureCollection includes one Capture object for each captured substring, and the Group object provides information only about the last captured substring.

以及链接文档中提供的示例:

  // 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);
  }

关于c# - 正则表达式匹配多个组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13689259/

相关文章:

java - 将零替换为单词中的字母 "o"

c# - Unity Player 抛出异常 : System. ArgumentException:找不到 'hideFlags' 的 Get 方法

C# 如何处理 TCP 包/段

java - 替换 Java 中的 ' 和类似标签

java - 正则表达式替换替换字符串

Java正则表达式包含2个值(内部相同的值)

C# - SQLClient - 最简单的 INSERT

c# - Linq 选择最高 ID,其中 ID 是字母数字

c# - WIN RT 中是否存在二进制序列化程序?

regex - Sublime text 2 搜索并替换为随机数