Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Regex group multiple captures

Tags:

c#

regex

The following code return 1:

Regex.Match("aaa", "(a)").Groups[1].Captures.Count

But I expect to receive 3: I see three captures of a.

like image 298
SiberianGuy Avatar asked Feb 11 '11 15:02

SiberianGuy


2 Answers

You need to either get the match count:

Regex.Matches("aaa", "(a)").Count

Or add a quantifier to the regex:

Regex.Match("aaa", "(a)+").Groups[1].Captures.Count

The regex (a) matches only a single a. In the first example above, that regex can be matched three times.

In the second example the regex matches several as at once and captures each one into group 1.

To make a choice you should consider the following differences between them:

Regex.Matches("aaba", "(a)").Count // this is 3
Regex.Match("aaba", "(a)+").Groups[1].Captures.Count // this is 2

The second only yields two captures because it matches the first sequence of two as but then it stops matching when it finds a b. The + quantifier only matches unbroken sequences.

like image 184
R. Martinho Fernandes Avatar answered Oct 12 '22 22:10

R. Martinho Fernandes


Use Regex.Matches method instead ?

like image 33
Steve B Avatar answered Oct 12 '22 20:10

Steve B