Reputation: 1097
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
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
Upvotes: 7