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

后端 未结 7 1525
野的像风
野的像风 2020-12-18 03:12

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

e.g.

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

7条回答
  •  有刺的猬
    2020-12-18 03:53

    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);
    

提交回复
热议问题