有人可以向我解释为什么以下语句的结果只有一个而不是一个?
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
Run Code Online (Sandbox Code Playgroud)
(我正在使用.NET 3.5的C#)
表达式在字符串的开头"*."匹配"foo",在结尾处匹配一个空字符串(位置3).记住,*意思是"零或更多".所以它匹配字符串末尾的"nothing".
这是一致的. Regex.Match(string.Empty, ".*");返回一个匹配:一个空字符串.