0

Let's say I have a text:

"His name is Jack. Jack likes to ride a bike"

What method would you recommend using to edit word "Jack" one by one, for example, I want to make specific changes for each "Jack". I've tried using Remove() and Replace(), but these methods edit all "Jack" in the text.

Reed
  • 1,161
  • 13
  • 25

1 Answers1

2

The Regex.Replace(String, MatchEvaluator) may be what you need. In the specified input string, it replaces all strings that match a specified regular expression with a string returned by a MatchEvaluator delegate.
So your MatchEvaluator delegate can decide what to replace every single "Jack" with.
For example:

string s = "His name is Jack. Jack likes to ride a bike";
int count = 0;
string s2 = Regex.Replace(s, "Jack", match => {
    count++;
    return count > 1 ? "Jack2" : "Jack1";
});

s2 is:

His name is Jack1. Jack2 likes to ride a bike

wingerse
  • 3,670
  • 1
  • 29
  • 61