Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex repetition group

Tags:

c#

regex

Capturing a repetition group is always returning the last element but that is not quite helpfull. For example:

var regex = new RegEx("^(?<somea>a)+$");
var match = regex.Match("aaa");
match.Group["somea"]; // return "a"

I would like to have a collection of match element instead of the last match item. Is that possible?

like image 577
mathk Avatar asked Feb 18 '23 08:02

mathk


1 Answers

CaptureCollection

You can use CaptureCollection which represents the set of captures made by a single capturing group.

If a quantifier is not applied to a capturing group, the CaptureCollection includes a single Capture object that represents the same captured substring as the Group object.

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.

So you can do this

var regex = new Regex("^(?<somea>a)+$");
var match = regex.Match("aaa");
List<string> aCaptures=match.Groups["somea"]
                            .Captures.Cast<Capture>()
                            .Select(x=>x.Value)
                            .ToList<string>();

//aCaptures would now contain a list of a
like image 64
Anirudha Avatar answered Feb 21 '23 01:02

Anirudha