문제

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.

도움이 되었습니까?

해결책

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".

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top