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

时间:2018-03-27 07:40:07

标签: c# regex

以下是文字:

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]计数

2 个答案:

答案 0 :(得分:2)

您可以使用以下表达式:

(?<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#online上测试正则表达式,我使用http://regexhero.net/tester/(仅在IE中使用Silverlight ... O_o)

答案 1 :(得分:1)

您需要计算非空的所有第1组,第2组和第3组捕获组值:

var s = "There are many kids in the playground. It's about 1 23  45 5;中文等等";
var pattern = @"([0-9])|([a-zA-Z])|([\u4e00-\u9fa5])";
var ms = Regex.Matches(s, pattern).Cast<Match>();
var ascii_digit_cnt = ms.Select(x => x.Groups[1].Value).Where(n => !string.IsNullOrEmpty(n)).Count();
var ascii_letter_cnt = ms.Select(x => x.Groups[2].Value).Where(n => !string.IsNullOrEmpty(n)).Count();
var han_cnt = ms.Select(x => x.Groups[3].Value).Where(n => !string.IsNullOrEmpty(n)).Count();
Console.WriteLine($"{ascii_digit_cnt} : {ascii_letter_cnt} : {han_cnt}");
// => 6 : 39 : 4

请参阅C# demo

首先,您获得与Regex.Matches(s, pattern).Cast<Match>()的所有匹配。然后,您在x.Groups[1]中有ASCII数字匹配,x.Groups[2]中有ASCII字母匹配,x.Groups[3]中有汉字符。 .Where(n => !string.IsNullOrEmpty(n)删除所有空值(因为那些意味着组模式不匹配)。