Link to home
Start Free TrialLog in
Avatar of rye004
rye004Flag for United States of America

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.  

MatchEvaluator m;
int matchCount = 0;
string outputString;

currentFileText = Regex.Replace(currentFileText, currentRedactionRule.inputString, currentRedactionRule.patternString, m =>
    {
	matchCount++;
	return outputString;
    });

Open in new window


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.
Avatar of Jacques Bourgeois (James Burger)
Jacques Bourgeois (James Burger)
Flag of Canada image

Not directly.

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.
ASKER CERTIFIED SOLUTION
Avatar of rye004
rye004
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I did not know about that one. I am the one who learned something here.
Avatar of rye004

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.
Avatar of kaufmed
What is wrong with the code you originally posted?
Avatar of rye004

ASKER

This was the best answer.