是否有一个正则表达式的味道,让我来算匹配的*和+运营商重复的次数? [英] Is there a regex flavor that allows me to count the number of repetitions matched by the * and + operators?

查看:229
本文介绍了是否有一个正则表达式的味道,让我来算匹配的*和+运营商重复的次数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

      • <一个href="http://msdn.microsoft.com/en-us/library/system.text.regularex$p$pssions.capturecollection_members%28v=VS.100%29.aspx"><$c$c>CaptureCollection
      • 这篇关于是否有一个正则表达式的味道,让我来算匹配的*和+运营商重复的次数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆