2014-09-12 39 views
3

我想計算正則表達式在使用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匹配。但我似乎無法找到計算該數字的方法。任何人都可以幫忙嗎?

+0

這個問題不應該被作爲重複關閉。這個問題詢問有關統計*字符串出現在字符串中的次數,而[引用的問題](http://stackoverflow.com/questions/3016522)詢問了有關統計*固定字符串*的次數。 – DavidRR 2016-05-05 15:52:03

回答

3

對於這種特殊的情況下,你可以做這樣的事情:

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; 
2

相反Regex.Match的,使用Regex.Matches:

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

作爲一個規則,我一般投用MatchesIEnumerable<Match>所以它起着與LINQ不錯返回MatchCollection。你可能只是喜歡:

Regex.Matches(input, pattern).Count; 
相關問題