Count the number of regex matches in a string

I want to count the number of matches of a regex in a string using C #. I used this site to validate my regex: http://regexpal.com/

My regex:

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

      

And here is the input line:

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)

      

My expectation is that for my input string, my regex should give 8 matches. But I cannot find a way to calculate this number. Can anyone please help?

+3


source to share


2 answers


For this particular scenario, you can do something like this:

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

      

Item in Groups[0]

will be a complete match, so it won't be useful for what you need. Groups[1]

will contain the entire section (\\tChannel [0-9]* \(mV\))*

, which includes all repetitions. To get the number of repetitions, you use.Captures.Count

An example based on your example:

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;

      



Sorry for the bad formatting, but this should show you how it can be done, at least.

The examples given around Regex.Matches(...).Count

won't work here because it's one coincidence. You can't just use Regex.Match(...).Groups.Count

either because you only have one group, which leaves that with 2 groups returned from a match. You need to look at your specific group Regex.Match(...).Groups[1]

and get a counter from the number of captures in that group.

Also, you can name groups that can make it a little clearer to what's going on. Here's an example:

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;

      

+3


source


Use Regex.Matches instead of Regex.Match:

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

      



Generally, I usually pass the MatchCollection

returned Matches

one to IEnumerable<Match>

, so it works fine with linq. You might just prefer:

Regex.Matches(input, pattern).Count;

      

+2


source







All Articles