You can use the Regex
class and provide a delegate that will be called once for each match. It needs to return the string to replace the matched text with.
You simply have to declare a variable holding your counter:
string a = "**MustbeReplaced**asdgasfsff**MustbeReplaced**asdfafasfsa";
int replacementIndex = 0;
string b = Regex.Replace(a, "MustbeReplaced", match =>
{
replacementIndex++;
return $"Replaced{replacementIndex}";
});
After running this, b
will contain this:
**Replaced1**asdgasfsff**Replaced2**asdfafasfsa
Caution: Since you're now using the Regex
class, be aware of all the special characters that Regex
will use to augment the pattern away from simple character-by-character matching. If you're replacing text containing symbols like asterixes, question marks, parenthesis, etc. then you need to escape those.
Luckily we can simply ask the Regex
class to do that for us:
string a = "**Mustbe?Replaced**asdgasfsff**Mustbe?Replaced**asdfafasfsa";
int replacementIndex = 0;
string b = Regex.Replace(a, Regex.Escape("Mustbe?Replaced"), match =>
{
replacementIndex++;
return $"Replaced{replacementIndex}";
});