So I want to match a string with the word “cat” in it a bunch of times, such as:
"cat cat cat cat cat"
or
"cat cat cat cat"
If there’s anything else besides “cat” or whitespace, I don’t want to match. So I can do:
^(cat\s*)+$
However, I want to find out how many cats appear in the string. One way to do this would be to count the number of groups, however the above regular expression will only give me a single group with the first cat, not a capture per cat. Is there a way to do this using regular expressions?
You want to do two different things – validate a string and count word occurrences. Usually you cannot do these two things in one step.
In .NET regex you have Group.Captures which lists all the occurrences where a group matched, not just the last one, like in other regex engines. Here you could do both validating and counting in one step.