有人能解释一下这种行为(或者我做错了什么)吗?
//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: ""发布于 2014-03-04 01:59:29
组总是返回,因为它代表整个表达式。在您的示例中,match2.Groups[0].Success返回false,因为没有匹配。match.Groups[0].Success返回true,match.Groups[1]有匹配的组。
来自文档
由Match.Groups属性返回的GroupCollection对象始终至少有一个成员。如果正则表达式引擎无法在特定输入字符串中找到任何匹配项,则集合中单个组对象的Group.Success属性设置为false,而Group对象的值属性设置为String.Empty。如果正则表达式引擎能够找到匹配项,则组属性返回的GroupCollection对象的第一个元素包含与整个正则表达式模式匹配的字符串。如果正则表达式包括捕获组,则每个后续元素表示捕获的组。有关更多信息,请参见正则表达式文章中分组结构的“分组结构和正则表达式对象”部分。
https://stackoverflow.com/questions/22161353
复制相似问题