elevener
elevener

Reputation: 1097

Regex.Match and noncapturing groups

Can anyone explain why Regex.Match captures noncapturing groups. Can't find anything about it in MSDN. Why

Regex regexObj = new Regex("(?:a)");
Match matchResults = regexObj.Match("aa");
while (matchResults.Success)
{
    foreach (Capture g in matchResults.Captures)
    {
        Console.WriteLine(g.Value);
    }
    matchResults = matchResults.NextMatch();
}

produces output

a
a

instead of empty one?

Upvotes: 7

Views: 1141

Answers (1)

Petar Ivanov
Petar Ivanov

Reputation: 93020

Captures is different than groups.

matchResults.Groups[0]

is always the whole match. So your group would have been

matchResults.Groups[1],

if the regex were "(a)". Now since it's "(?:a)", you can check that it's empty.

Captures are a separate thing - they allow you to do something like this:

If you have the regex "(.)+", then it would match the string "abc".

Group[1] then would be "c", because that is the last group, while

  1. Groups[1].Captures[0] is "a"
  2. Groups[1].Captures[1] is "b"
  3. Groups[1].Captures[2] is "c".

Upvotes: 7

Related Questions