Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing text using regular expression with variable text?

Tags:

c#

regex

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.

like image 870
Priyank Bolia Avatar asked Apr 12 '26 08:04

Priyank Bolia


2 Answers

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;
});
like image 154
Marc Gravell Avatar answered Apr 14 '26 21:04

Marc Gravell


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; });
like image 41
Greg Beech Avatar answered Apr 14 '26 22:04

Greg Beech



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!