比如正则表达式为:
([0-9])|([a-zA-Z])|([\u4e00-\u9fa5])
文本为:
输入10个1-100的整数,生成一个排序二叉树,使得其中序遍历结果是有序的输出。要求:必须使用JAVA语言,开发环境随意。输入:10个1-100的整数输出:按中序遍历输出二叉树,再按层次遍历输出二叉树
在c#中能否提取出比如符合第一个匹配[0-9] 的数量,还有[a-zA-Z]的数量等等。
目前只能获取到全部匹配的数量。
献上两位大佬的回答:
You can use this expression:
(?<digit>[0-9])|(?<letter>[a-zA-Z])|(?<ucode>[\u4e00-\u9fa5])
in that code:
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);
}
In a single iteration counts all matches.
Note: To test regular expressions on c# online I use http://regexhero.net/tester/ (Silverlight only in IE... O_o)
第二位:
You need to count all Group 1, 2 and 3 capture group values that are not empty:
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
At first, you get all matches with Regex.Matches(s, pattern).Cast<Match>(). Then, you have ASCII digit matches in x.Groups[1], ASCII letter matches in x.Groups[2] and Han chars in x.Groups[3]. The .Where(n => !string.IsNullOrEmpty(n) removes all empty values (as those mean the group pattern did not match).
其实Regex pattern 中不用指定Group name 也可以,直接用Groups[1], Groups[2] 来表示第一个match和第二个就可以了