C # Regex Group Records

The following code returns 1:

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

But I expect to get 3: I see three captures.

+4
source share
2 answers

You need to either get a hit counter:

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

Or add a quantifier to the regular expression:

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

Regular expression (a) matches only one a . In the first example above, this regular expression can be matched three times.

In the second example, the regular expression matches several a once and captures each of them in group 1.

To make a choice, you must 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 result gives only two captures, since it corresponds to the first sequence of two a , but then stops matching when it finds b . The coefficient + corresponds only to unbreakable sequences.

+9
source

Use the Regex.Matches method instead <

+2
source

Source: https://habr.com/ru/post/1339378/


All Articles