Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
378 views
in Technique[技术] by (71.8m points)

c# - Regex failing to match inner repeatable occurrences

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

Input string: =F2=0B=E2some text =C2=A3
Regex: (=([0-9A-F][0-9A-F]))+

The capturing groups it returns is:

Group 1:

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

Group 2:

  • E2
  • A3

But I need Group 2 to return:

  • F2
  • 0B
  • E2

and

  • C2
  • A3

within each outer group.

Is this possible somehow?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You just need to access the match.Groups[2].Captures collection.

See the regex demo

enter image description here

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

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.)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...