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.
See Question&Answers more detail:os