有一个正则表达式的味道,让我来算匹配由重复的次数 *
和 +
运营商?我特别想知道,如果可能的.NET平台下。
Is there a regex flavor that allows me to count the number of repetitions matched by the *
and +
operators? I'd specifically like to know if it's possible under the .NET Platform.
您很幸运,因为实际上.NET正则表达式做到这一点(我认为这是很独特)。基本上在每一个匹配
,每个集团
商店每捕获
的写了。
You're fortunate because in fact .NET regex does this (which I think is quite unique). Essentially in every Match
, each Group
stores every Captures
that was made.
所以,你可以指望有多少次重复的图案由匹配输入:
So you can count how many times a repeatable pattern matched an input by:
使其成为一个捕获组 在计数多少捕获由该组中的每场比赛都取得了 您可以通过个人的捕获循环太多,如果你想要的! Making it a capturing group Counting how many captures were made by that group in each match You can iterate through individual capture too if you want!下面是一个例子:
Regex r = new Regex(@"b(hu?a)+b");
var text = "hahahaha that's funny but not huahuahua more like huahahahuaha";
foreach (Match m in r.Matches(text)) {
Console.WriteLine(m + " " + m.Groups[1].Captures.Count);
}
此照片(因为看到ideone.com ):
hahahaha 4
huahuahua 3
huahahahuaha 5