[英]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.