C# 字符串中令牌的计数

C# 字符串中令牌的计数,c#,regex,C#,Regex,我真的很奇怪为什么下面的代码返回1而不是2。有线索吗?提前谢谢 string report = "foo bar foo aloha hole hole foo cat gag weird gag strange tourist"; string name = "hole"; int count = Regex.Matches(report, @"(^|\s)" + Regex.Escape(name) + @"(\s|$)").Count; Console.WriteLine("count

我真的很奇怪为什么下面的代码返回1而不是2。有线索吗?提前谢谢

string report = "foo bar foo aloha hole hole foo cat gag weird gag strange tourist";
string name = "hole";

int count = Regex.Matches(report, @"(^|\s)" + Regex.Escape(name) + @"(\s|$)").Count;
Console.WriteLine("count is " + c);

因为第一个匹配会占用单词
周围的空格,所以无法匹配第二个

aloha hole hole foo
     ^    ^
您最好改用单词boundary
\b

int count = Regex.Matches(report, @"\b" + Regex.Escape(name) + @"\b").Count;

如果你只是想学习
Regex
,那就冷静点,忽略这个

否则,
Regex
对于使用其他方法(如
LINQ
)实现如此简单的功能来说是过分的:


\b可以工作,但它将“hole”、“hole”、“hole?”计算为一个单词的三次出现,这在我的情况下是不够的。@iwtu,那么使用use lookaround断言如何
@”(?@falsetrue这是我想要的。我不知道lookaround断言。我会检查它。谢谢:)谢谢。这和我想要的完全一样。我也会学习一些关于LINQ的知识。顺便说一句,正则表达式太贵了?
var count = report.Split().Count(x => x == name);