gpt4 book ai didi

c# - 统计正则表达式在字符串中匹配的次数

转载 作者:行者123 更新时间:2023-11-30 14:55:15 24 4
gpt4 key购买 nike

我想使用 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 个匹配项。但我似乎找不到计算该数字的方法。有人可以帮忙吗?

最佳答案

对于这个特定的场景,你可以这样做:

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;

关于c# - 统计正则表达式在字符串中匹配的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25807208/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com