【问题标题】:Count number of times a regular expression is matched in a string计算正则表达式在字符串中匹配的次数
【发布时间】:2014-11-06 13:39:29
【问题描述】:

我想使用 C# 计算字符串中正则表达式匹配的次数。我使用这个网站来帮助验证我的正则表达式:http://regexpal.com/

我的正则表达式是:

Time(\\tChannel [0-9]* \(mV\))*

这是输入字符串:

Time\tChannel 1 (mV)\tChannel 2 (mV)\tChannel 3 (mV)\tChannel 4 (mV)\tChannel 5 (mV)\tChannel 6 (mV)\tChannel 7 (mV)\tChannel 8 (mV)\tChannel 1_cal (mg/L)\tChannel 2_cal ()\tChannel 3_cal ()\tChannel 4_cal ()\tChannel 5_cal ()\tChannel 6_cal ()\tChannel 7_cal ()\tChannel 8_cal ()\tMotor 1 (mm)\tMotor 2 (mm)

我的期望是,对于我的输入字符串,我的正则表达式应该产生 8 个匹配项。但我似乎找不到计算这个数字的方法。有人可以帮忙吗?

【问题讨论】:

  • 这个问题不应该作为重复而关闭。这个问题询问关于计算 pattern 在字符串中出现的次数,而 referenced question 询问关于计算 fixed string 的次数。

标签: c# regex


【解决方案1】:

对于这种特殊情况,您可以执行以下操作:

Regex.Match(input, pattern).Groups[1].Captures.Count

Groups[0] 中的元素将是整个匹配项,因此这对您的需要没有帮助。 Groups[1] 将包含整个 (\\tChannel [0-9]* \(mV\))* 部分,其中包括所有重复。要获得它重复的次数,请使用.Captures.Count

基于您的示例的示例:

Regex.Match(
    @"Time\tChannel 1 (mV)\tChannel 2 (mV)\tChannel 3 (mV)\tChannel 4 (mV)\tChannel 5 (mV)\tChannel 6 (mV)\tChannel 7 (mV)\tChannel 8 (mV)\tChannel 1_cal (mg/L)\tChannel 2_cal ()\tChannel 3_cal ()\tChannel 4_cal ()\tChannel 5_cal ()\tChannel 6_cal ()\tChannel 7_cal ()\tChannel 8_cal ()\tMotor 1 (mm)\tMotor 2 (mm)", 
    @"Time(\\tChannel [0-9]* \(mV\))*"
).Groups[1].Captures.Count;

我为那里糟糕的格式道歉,但这至少应该告诉你如何做到这一点。

围绕Regex.Matches(...).Count 给出的示例在这里不起作用,因为它是一个匹配项。您也不能只使用Regex.Match(...).Groups.Count,因为您只指定了一个组,这使得比赛返回了 2 个组。您需要查看您的特定组 Regex.Match(...).Groups[1] 并从该组中的捕获数中获取计数。

此外,您还可以为组命名,这样可以更清楚地了解正在发生的事情。这是一个例子:

Regex.Match(
    @"Time\tChannel 1 (mV)\tChannel 2 (mV)\tChannel 3 (mV)\tChannel 4 (mV)\tChannel 5 (mV)\tChannel 6 (mV)\tChannel 7 (mV)\tChannel 8 (mV)\tChannel 1_cal (mg/L)\tChannel 2_cal ()\tChannel 3_cal ()\tChannel 4_cal ()\tChannel 5_cal ()\tChannel 6_cal ()\tChannel 7_cal ()\tChannel 8_cal ()\tMotor 1 (mm)\tMotor 2 (mm)", 
    @"Time(?<channelGroup>\\tChannel [0-9]* \(mV\))*"
).Groups["channelGroup"].Captures.Count;

【讨论】:

    【解决方案2】:

    使用 Regex.Match 代替 Regex.Match:

    Regex.Matches(input, pattern).Cast<Match>().Count();
    

    通常,我通常将Matches 返回的MatchCollection 转换为IEnumerable&lt;Match&gt;,因此它与linq 配合得很好。您可能更喜欢:

    Regex.Matches(input, pattern).Count;
    

    【讨论】:

      猜你喜欢
      • 2012-08-07
      • 1970-01-01
      • 2011-06-21
      • 1970-01-01
      • 2019-09-20
      • 2015-07-31
      相关资源
      最近更新 更多