對於這種特殊的情況下,你可以做這樣的事情:
Regex.Match(input, pattern).Groups[1].Captures.Count
在Groups[0]
元素將是整場比賽,所以這不是您所需要的幫助。 Groups[1]
將包含整個(\\tChannel [0-9]* \(mV\))*
部分,其中包含所有重複。爲了讓您使用基於你的榜樣.Captures.Count
樣品它repeates次數:
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
,因爲您只指定了一個組,這會使該組與剩下的兩組相匹配。您需要查看您的特定組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;
這個問題不應該被作爲重複關閉。這個問題詢問有關統計*字符串出現在字符串中的次數,而[引用的問題](http://stackoverflow.com/questions/3016522)詢問了有關統計*固定字符串*的次數。 – DavidRR 2016-05-05 15:52:03