How do I replace a specific occurrence of a string in a string?

This will only replace the second instance of title1 (and any subsequent instances) after the first:

string output = Regex.Replace(input, @"(?<=title1.*)title1", "title2");

However, if there are more than 2 instances, it may not be what you want. It's a little crude, but you can do this to handle any number of occurrences:

int i = 1;
string output = Regex.Replace(input, @"title1", m => "title" + i++);

You can use the regex replace MatchEvaluator and give it a "state":

string callingURL = @"server/api/shows?title1=its always sunny in philadelphia&title1=breaking bad";

int found = -1;
string callingUrl2 = Regex.Replace(callingURL, "title1=", x =>
{
    found++;
    return found == 1 ? "title2=" : x.Value;
});

The replace can be one-lined by using the postfixed ++ operator (quite unreadable).

string callingUrl2 = Regex.Replace(callingURL, "title1=", x => found++ == 1 ? "title2=" : x.Value);

Here is a C# extension method I created for a similar task that may come in handy.

internal static class ExtensionClass
{
    public static string ReplaceNthOccurrence(this string obj, string find, string replace, int nthOccurrence)
    {
        if (nthOccurrence > 0)
        {
            MatchCollection matchCollection = Regex.Matches(obj, Regex.Escape(find));
            if (matchCollection.Count >= nthOccurrence)
            {
                Match match = matchCollection[nthOccurrence - 1];
                return obj.Remove(match.Index, match.Length).Insert(match.Index, replace);
            }
        }
        return obj;
    }
}

Then you can use it with the following example.

"computer, user, workstation, description".ReplaceNthOccurrence(",", ", and", 3)

Which will produce the following.

"computer, user, workstation, and description"

OR

"computer, user, workstation, description".ReplaceNthOccurrence(",", " or", 1).ReplaceNthOccurrence(",", " and", 2)

Will produce the below.

"computer or user, workstation and description"

I hope this helps someone else who had the same question.

Tags:

C#

String

Regex