有人可以向我解释为什么以下语句的结果计数为二而不是一吗?
MatchCollection matches = new Regex( ".*" ).Matches( "foo" ) ;
Assert.AreEqual( 1, matches.Count ) ; // will fail!
new Regex( ".+" ).Matches( "foo" ) ; // returns one match (as expected)
new Regex( ".*" ).Matches( "" ) ; // also returns one match
(我使用的是 .NET 3.5 的 C#)
最佳答案
表达式 "*."
匹配字符串开头的 "foo"
以及结尾处的空字符串(位置 3)。请记住,*
表示“零个或多个”。所以它匹配字符串末尾的“nothing”。
这是一致的。 Regex.Match(string.Empty, ".*");
返回一个匹配项:空字符串。
关于C# Regex.Matches 返回太多匹配项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3789648/