Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
238 views
in Technique[技术] by (71.8m points)

c# - How do I replace a specific occurrence of a string in a string?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...