我如何替换字符串字符串的具体发生? [英] How do I replace a specific occurrence of a string in a string?

查看:123
本文介绍了我如何替换字符串字符串的具体发生?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有可能含有TITLE1两次它的字符串。

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

例如

服务器/ API /节目TITLE1 =它总是在费城和放阳光充足; TITLE1 =破坏...

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

我需要的单词TITLE1的第二个实例更改为标题2

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?

推荐答案

这将只替换 TITLE1 (和任何后续实例)后的第一次:

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

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



不过,如果有超过2的情况下,它可能不是你想要的。这是一个有点粗糙,但你可以做到这一点,以处理任何数量出现的:

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

这篇关于我如何替换字符串字符串的具体发生?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆