Skip to main content
 首页 » 编程设计

c#之我可以在 C# 中获取每个正则表达式组匹配计数吗

2024年02月25日30qlqwjy

正文如下:

There are many kids in the playground. It's about 1 23  45 5;中文等等 

这是我使用的正则表达式模式 ([0-9])|([a-zA-Z])|([\u4e00-\u9fa5])" 我想得到三个匹配组的个数:pattern1 [0-9] 的个数是6; [\u4e00-\u9fa5] 计数是4,有没有可能计算出来。

我试过了

var characterMatch = characterPattern.Matches(content) 

但我只得到所有匹配计数是 49。那么,有可能得到不同的部分计数吗?

我期望得到的是匹配 [0-9] 计数,匹配 [a-zA-Z] 计数

请您参考如下方法:

你可以使用这个表达式:

(?<digit>[0-9])|(?<letter>[a-zA-Z])|(?<ucode>[\u4e00-\u9fa5]) 

在该代码中:

string strRegex = @"(?<digit>[0-9])|(?<letter>[a-zA-Z])|(?<ucode>[\u4e00-\u9fa5])"; 
Regex myRegex = new Regex(strRegex, RegexOptions.IgnoreCase | RegexOptions.Multiline); 
string strTargetString = @"There are many kids in the playground. It's about 1 23  45 5;????"; 
 
int digits = 0; 
int letters = 0; 
int ucode = 0; 
foreach (Match myMatch in myRegex.Matches(strTargetString)) 
{ 
    digits += (!string.IsNullOrEmpty(myMatch.Groups["digit"].Value) ? 1 : 0); 
    letters += (!string.IsNullOrEmpty(myMatch.Groups["letter"].Value) ? 1 : 0); 
    ucode += (!string.IsNullOrEmpty(myMatch.Groups["ucode"].Value) ? 1 : 0); 
} 

在单次迭代中计算所有匹配项。

注意:为了在 c# 上在线测试正则表达式,我使用 http://regexhero.net/tester/ (Silverlight 仅在 IE 中... O_o)