rye004
asked on
Can I determine how many changes Regex.Replace has made in C#?
I am trying to use the code below to make changes and tell me the number of changes that have been made.
I would prefer not to use a MatchCollection and a foreeach outside of this call. Performance is important to me and I would rather get this value if it already exists.
Hopefully this makes sense. Any help would be greatly appreciated.
MatchEvaluator m;
int matchCount = 0;
string outputString;
currentFileText = Regex.Replace(currentFileText, currentRedactionRule.inputString, currentRedactionRule.patternString, m =>
{
matchCount++;
return outputString;
});
I would prefer not to use a MatchCollection and a foreeach outside of this call. Performance is important to me and I would rather get this value if it already exists.
Hopefully this makes sense. Any help would be greatly appreciated.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
I did not know about that one. I am the one who learned something here.
ASKER
It works, but I have to evaluate the text twice when there is a match. I would prefer a way to only call the Regex class once. I will leave this question open for a bit to see if anyone else has any ideas.
Thanks again for your help.
Thanks again for your help.
What is wrong with the code you originally posted?
ASKER
This was the best answer.
But at the detriment of a small price in performance (maybe a big price if you expect a lot of replacements), you could do the job in a while loop, with the overload of Replace that limits the number of replacements to perform. Simply set that parameter to 1, loop for as long as the string changes (compare the returned value with the original value) and count the number of turns in the loop.
If the replacement is a straight one, you could also use string.IndexOf in a loop to count the number of instances of the string to be replaced before you do the job.
Or use string.DistincOf to look for that string and get the count on the returned array.