Lets say I have some text with lots of instances of word "Find", which I want to replace it with text like "Replace1","Replace2","Replace3", etc. The number is the occurrence count of "Find" in the text. How to do it in the most effective way in C#, I already know the loop way.
+3
A:
You could use the overload that takes a MatchEvaluator
and provide the custom replacement string inside the delegate implementation, which would allow you to do all the replacements in one pass.
For example:
var str = "aabbccddeeffcccgghhcccciijjcccckkcc";
var regex = new Regex("cc");
var pos = 0;
var result = regex.Replace(str, m => { pos++; return "Replace" + pos; });
Greg Beech
2009-04-21 09:56:35
+4
A:
A MatchEvaluator
can do this:
string input = "FindbcFinddefFind", pattern = "Find";
int i = 1;
string replaced = Regex.Replace(input, pattern, match => "REPLACE" + i++);
Note that the match
variable also has access to the Match
etc. With C# 2.0 you'll need to use an anonymous method rather than a lambda (but same effect) - to show both this and the Match
:
string input = "FindbcFinddefFind", pattern = "Find";
int i = 1;
string replaced = Regex.Replace(input, pattern, delegate(Match match)
{
string s = match.Value.ToUpper() + i;
i++;
return s;
});
Marc Gravell
2009-04-21 09:58:37