正则表达式无法匹配内部可重复出现 [英] Regex failing to match inner repeatable occurrences

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

问题描述

我无法多次匹配嵌套的捕获组,结果只给了我 last 内部捕获。

I'm failing to match a nested capturing group multiple times, the result only gives me the last inner capture instead.

输入字符串: = F2 = 0B = E2某些文本= C2 = A3

正则表达式:(\ =([0-9A -F] [0-9A-F]))+

返回的捕获组为:

组1:


  • = F2 = 0B = E2

  • = C2 = A3

  • =F2=0B=E2
  • =C2=A3

第2组:


  • E2

  • A3

  • E2
  • A3

但是我需要第2组返回:

But I need Group 2 to return:


  • F2

  • 0B

  • E2

  • F2
  • 0B
  • E2


  • C2

  • A3

  • C2
  • A3

在每个外部组中。

这有可能吗?

推荐答案

您只需要访问 match.Groups [2]。捕获集合。

请参见 regex演示

< img src = https://i.stack.imgur.com/tb6Vc.png alt =在此处输入图片描述>

您所拥有的需要的是 CaptureCollection 。参见 Regex.Match 引用

What you need is a CaptureCollection. See this Regex.Match reference:


捕获

获取捕获组匹配的所有捕获的集合,按照最里面的最左第一顺序(如果使用最里面的最右第一顺序)正则表达式使用 RegexOptions.RightToLeft 选项进行修改)。该集合可能具有零个或多个项目。(继承自Group。)

Captures
Gets a collection of all the captures matched by the capturing group, in innermost-leftmost-first order (or innermost-rightmost-first order if the regular expression is modified with the RegexOptions.RightToLeft option). The collection may have zero or more items.(Inherited from Group.)

这里是示例演示,该示例演示从 Groups [2] CaptureCollection( F2 0B E2 C2 A3 ):

Here is a sample demo that outputs all the captures from Groups[2] CaptureCollection (F2, 0B, E2, C2, A3):

var pattern = "(=([0-9A-F]{2}))+";
var result = Regex.Matches("=F2=0B=E2some text =C2=A3", pattern)
          .Cast<Match>().Select(p => p.Groups[2].Captures)
          .ToList();
foreach (var coll in result)
   foreach (var v in coll)
        Console.WriteLine(v);

这篇关于正则表达式无法匹配内部可重复出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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