Replacing text using regex with variable text?

Let's say that I have text with a lot of examples of the word “Find”, which I want to replace with text like “Replace1”, “Replace2”, “Replace3”, etc. Number is the number of occurrences of Find in the text. How to do this in the most efficient way in C #, I already know the loop path.

+3
source share
2 answers

A MatchEvaluatorcan do this:

string input = "FindbcFinddefFind", pattern = "Find";
int i = 1;
string replaced = Regex.Replace(input, pattern, match => "REPLACE" + i++);

Note that the variable matchalso has access to match, etc. With C # 2.0, you will need to use an anonymous method, not a lambda (but the same effect), to show both this and this 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;
});
+5

, MatchEvaluator , .

:

var str = "aabbccddeeffcccgghhcccciijjcccckkcc";
var regex = new Regex("cc");
var pos = 0;
var result = regex.Replace(str, m => { pos++; return "Replace" + pos; });
+3

Source: https://habr.com/ru/post/1706809/