Skip to main content
 首页 » 编程设计

c#之使用 Regex.Matches 计算字符串中的特定单词时出错

2024年02月06日36langtianya

我试图找到一种方法来计算字符串中的特定单词,我找到了这个。

using System.Text.RegularExpressions; 
 
MatchCollection matches = Regex.Matches("hi, hi, everybody.", ","); 
int cnt = matches.Count; 
Console.WriteLine(cnt); 

运行正常,结果显示2。 但是,当我将“,”更改为“.”时,它显示的是 18,而不是预期的 1。为什么?

MatchCollection matches = Regex.Matches("hi, hi, everybody.", "."); 

当我将“,”更改为“(”时,它显示错误! 错误是:

SYSTEM.ARGUMENTEXCEPTION - THERE ARE TOO MANY (... 

我不明白为什么会这样

MatchCollection matches = Regex.Matches("hi( hi( everybody.", "("); 

其他情况似乎工作正常但我需要计算“(”。

请您参考如下方法:

第一个例子是 .,它使用了一个在正则表达式中具有不同含义的特殊字符。它匹配您拥有的所有字符;因此你得到 18 的结果。

http://www.regular-expressions.info/dot.html

匹配实际的“.”字符,您需要对其进行“转义”,以便将其读作句号而不是特殊字符。

MatchCollection matches = Regex.Matches("hi, hi, everybody.", "\."); 

( 字符也是如此。它是一个特殊字符,在正则表达式中具有不同的含义,您需要对其进行转义。

MatchCollection matches = Regex.Matches("hi( hi( everybody.", "\("); 

看来您是正则表达式的新手,所以我建议您阅读,我上面发布的链接是一个好的开始。

然而!

如果您只想计算字符串中出现的次数,则不需要正则表达式。

How would you count occurrences of a string within a string?

如果您使用的是 .NET 3.5,则可以使用 LINQ 在一行中执行此操作:

int cnt = source.Count(f => f == '('); 

如果你不想使用 LINQ,你可以这样做:

int cnt = source.Split('(').Length - 1;