Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

c#

regex

I have a string which may contain "title1" twice in it.

e.g.

server/api/shows?title1=its always sunny in philadelphia&title1=breaking bad ...

I need to change the second instance of the word "title1" to "title2"

I already know how to identify whether there ARE two instances of the string in the string.

int occCount = Regex.Matches(callingURL, "title1=").Count;

if (occCount > 1)
{
     //here's where I need to replace the second "title1" to "title2"
}

I know we can probably use Regex here but I'm not able to get the replace on the second instance. Can anyone give me a hand?

like image 916
JJ. Avatar asked Jun 26 '13 16:06

JJ.


2 Answers

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++);
like image 113
p.s.w.g Avatar answered Sep 18 '22 15:09

p.s.w.g


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);
like image 33
xanatos Avatar answered Sep 19 '22 15:09

xanatos