简体   繁体   English

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

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

Can someone explain to me why the result from the following statement has a count of two an not just one? 有人可以向我解释为什么以下语句的结果为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 

(I'm using C# of .NET 3.5) (我正在使用C#的.NET 3.5)

The expression "*." 表达式"*." matches "foo" at the start of the string, and an empty string at the end (position 3). 在字符串的开头匹配"foo" ,在结尾(位置3)匹配一个空字符串。 Remember, * means, "zero or more". 请记住, *表示“零或更多”。 So it matches "nothing" at the end of the string. 因此,它在字符串末尾匹配“ nothing”。

This is consistent. 这是一致的。 Regex.Match(string.Empty, ".*"); returns one match: an empty string. 返回一个匹配项:一个空字符串。

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

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

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

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