简体   繁体   中英

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?

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)

The expression "*." matches "foo" at the start of the string, and an empty string at the end (position 3). Remember, * means, "zero or more". So it matches "nothing" at the end of the string.

This is consistent. Regex.Match(string.Empty, ".*"); returns one match: an empty string.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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