繁体   English   中英

C#Regex.Matches返回太多匹配项?

[英]C# Regex.Matches returns too many matches?

有人可以向我解释为什么以下语句的结果为2而不是1的计数吗?

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 

(我正在使用C#的.NET 3.5)

表达式"*." 在字符串的开头匹配"foo" ,在结尾(位置3)匹配一个空字符串。 请记住, *表示“零或更多”。 因此,它在字符串末尾匹配“ nothing”。

这是一致的。 Regex.Match(string.Empty, ".*"); 返回一个匹配项:一个空字符串。

包括“ ^”,将匹配的表达式锚定在输入字符串的开头。

MatchCollection matches = new Regex( "^.*" ).Matches( "foo" ) ;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM