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
You can use a MatchEvaluator
that runs for each replacement, that way you can count how many times it occurs:
int cnt = 0;
string result = Regex.Replace("aaa", "a", m => {
cnt++;
return "b";
});
The second case is trickier as you have to produce the same result as the replacement pattern would:
int cnt = 0;
string result = Regex.Replace("aaa", "(?aa?)", m => {
cnt++;
return m.Groups["test"] + "b";
});