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

标签 c# regex .net-3.5

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

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 

(我使用的是 .NET 3.5 的 C#)

最佳答案

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

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

关于C# Regex.Matches 返回太多匹配项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3789648/

相关文章:

c# - 创建自动生成的整数不起作用

c# - 如何按模式重写字符串

c# - Windows Phone 应用程序统一构建的错误证书

c# - 许多文本框的 onTextChanged 事件 c#

javascript - 正则表达式匹配 A、AB、ABC,但不匹配 AC。 ("starts with")

regex - 使用 Notepad++ 双换行符

java - 查找 XML 标记值的正确正则表达式 - java

.net - 从 CheckedListBox.Items 绑定(bind)启用属性 - Winforms

c# - 何时在 LINQtoObjects 上使用带有 lambda 的扩展方法来过滤集合?

.net-3.5 - 将应用程序池的 .NET Framework 版本更改为 3.5?