Shaokan
Shaokan

Reputation: 7684

Match.Groups[].Value returns repeated values

The input is 55, and my regex is ^(5{2})$. So ideally (at least to me) this should return every string that starts with a 5 and ends with a 5 right?

But when my c# is like the following:

Match match = Regex.Match(input, String.Format(@"{0}", regex));
string outcome = null;

if (match.Success)
{
    for (int i = 0; i < match.Groups.Count; i++)
    {
        outcome += match.Groups[i].Value;
    }
}

Why does my string outcome returns 5555 instead of 55?

When I remove the brackets from the regex it works perfectly.

Upvotes: 0

Views: 209

Answers (1)

BoltClock
BoltClock

Reputation: 724152

The first item in match.Groups contains the entire match that's picked up by your regex. The second item is what's captured in the brackets.

Since the regex and input are essentially the same string "55", you get two identical matches: one for the entire input matched, and one for the capture group (the brackets).

Both of these are concatenated and you get "55" + "55", which is "5555".

Upvotes: 4

Related Questions