是否有一个正则表达式的味道,让我来算匹配的*和+运营商重复的次数?我来、运营商、有一个、味道

2023-09-02 10:24:12 作者:生而在世

有一个正则表达式的味道,让我来算匹配由重复的次数 * + 运营商?我特别想知道,如果可能的.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

API参考

CaptureCollection

 
精彩推荐
图片推荐