Pergunta

Can someone explain this behaviour (or what I'm doing wrong):

//matches twice (should only match once)
Regex regex = new Regex("(?<=Start )(.*)(?= End)");
Match match = regex.Match("Start blah End");
Console.Out.WriteLine("Groups:" + match.Groups.Count + " " + match.Groups[0] + " " + match.Groups[0]);  //2 groups: "blah" and "blah"

//matches once, but blank result (should not match)
Match match2 = regex.Match("Shouldn't match at all");
Console.Out.WriteLine("Groups:" + match2.Groups.Count + " " + match2.Groups[0]);  //1 group: ""
Foi útil?

Solução

Groups[0] is always returned, as it represents the entire expression. In your case match2.Groups[0].Success returns false, since there is no match. match.Groups[0].Success returns true, and match.Groups[1] has the matching group.

From the documentation:

The GroupCollection object returned by the Match.Groups property always has at least one member. If the regular expression engine cannot find any matches in a particular input string, the Group.Success property of the single Group object in the collection is set to false and the Group object's Value property is set to String.Empty. If the regular expression engine can find a match, the first element of the GroupCollection object returned by the Groups property contains a string that matches the entire regular expression pattern. Each subsequent element represents a captured group, if the regular expression includes capturing groups. For more information, see the "Grouping Constructs and Regular Expression Objects" section of the Grouping Constructs in Regular Expressions article.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top