Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...