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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With