mathk
mathk

Reputation: 8133

Regex repetition group

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?

Upvotes: 4

Views: 1105

Answers (4)

Anirudha
Anirudha

Reputation: 32797

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

Upvotes: 6

Javier Diaz
Javier Diaz

Reputation: 1830

You must use the quantifier + to the thing you want to match, not the group, if you quantify the group that will create as many groups as matches are.

So (a)+ in aaa Will create 1 group and will replace the match with the new occurrence of the match and (a+) will create 1 group with aaa

So you know what to do with your problem, just move the + inside the capturing group.

Upvotes: 0

Nick.T
Nick.T

Reputation: 577

You can also try something like this :

var regex = new RegEx("^(?<somea>a)+$");
var matches = regex.Matches("aaa");
foreach(Match _match in matches){
    match.Group["somea"]; // return "a"
}

This is just a sample but it should give a good start. I did not check the validity of your regular expression though

Upvotes: 0

CyberDude
CyberDude

Reputation: 8959

Take a look in the Captures collection:

match.Groups["somea"].Captures

Upvotes: 2

Related Questions