正则表达式匹配多个组 [英] Regex match multiple groups

查看:139
本文介绍了正则表达式匹配多个组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following example of a string with regex which I am trying to match:

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

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

我的问题是-正则表达式匹配并捕获1组-字符串末尾的最后 00 .但是,我希望它与末尾的所有三个 00 组匹配.为什么不起作用?括号肯定意味着它们都相等匹配吗?

My question is this - the regex matches and captures 1 group - the final 00 at the end of the string. However, I want it to match all three of the 00 groups at the end. Why doesn't this work? Surely the brackets should mean that they are all matched equally?

我知道我可以分别输入这三个组,但这只是更长字符串的一小部分内容,所以很痛苦.我希望这会提供一个更优雅的解决方案,但似乎我的理解有些欠缺!

I know that I could just type out the three groups separately but this is just a short extract of a much longer string so that would be a pain. I was hoping that this would provide a more elegant solution but it seems my understanding is lacking somewhat!

谢谢!

推荐答案

由于捕获组中有一个量词,因此您只能看到上次迭代中的捕获.不过,对您来说幸运的是,.NET(与其他实现不同)提供了一种机制,可通过

Because you have a quantifier on a capture group, you're only seeing the capture from the last iteration. Luckily for you though, .NET (unlike other implementations) provides a mechanism for retrieving captures from all iterations, via the CaptureCollection class. From the linked documentation:

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

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.

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

And the example provided from the linked documentation:

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

这篇关于正则表达式匹配多个组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆