Is there a way to count the number of replacements a Regex.Replace call makes?
E.g. for Regex.Replace("aaa", "a", "b");
I want to get the number 3 out (result is "bbb"
); for Regex.Replace("aaa", "(?<test>aa?)", "${test}b");
I want to get the number 2 out (result is "aabab"
).
Ways I can think to do this:
- Use a MatchEvaluator that increments a captured variable, doing the replacement manually
- Get a MatchCollection and iterate it, doing the replacement manually and keeping a count
- Search first and get a MatchCollection, get the count from that, then do a separate replace
Methods 1 and 2 require manual parsing of $ replacements, method 3 requires regex matching the string twice. Is there a better way.
This should do it.
I am not on my dev computer so I can't do it right now, but I am going to experiment later and see if there is a way to do this with lambda expressions instead of declaring the method IncrementCount() just to increment an int.EDIT modified to use a lambda expression instead of declaring another method.
EDIT2 If you don't know the pattern in advance, you can still get all the groupings (The $ groups you refer to) within the match object as they are included as a GroupCollection. Like so:
Thanks to both Chevex and Guffa. I started looking for a better way to get the results and found that there is a Result method on the Match class that does the substitution. That's the missing piece of the jigsaw. Example code below:
With a file test.txt containing aaa, the command line
regexrep test.txt "(?<test>aa?)" ${test}b
will set %errorlevel% to 2 and change the text to aabab.You can use a
MatchEvaluator
that runs for each replacement, that way you can count how many times it occurs:The second case is trickier as you have to produce the same result as the replacement pattern would: