3

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.

2 Answers 2

5

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;
});
Sign up to request clarification or add additional context in comments.

Comments

3

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; });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.