我有一个字符串,其中可能包含两次"title1".
例如
server/api/shows?title1 =它在费城总是阳光充足&title1 =破坏...
我需要将单词"title1"的第二个实例更改为"title2"
我已经知道如何识别字符串中是否有两个字符串实例.
int occCount = Regex.Matches(callingURL, "title1=").Count;
if (occCount > 1)
{
//here's where I need to replace the second "title1" to "title2"
}
Run Code Online (Sandbox Code Playgroud)
我知道我们可以在这里使用Regex但是我无法在第二个实例上获得替换.任何人都可以帮我一把吗?
p.s*_*w.g 12
这只会在第一个实例之后替换第二个实例title1(和任何后续实例):
string output = Regex.Replace(input, @"(?<=title1.*)title1", "title2");
Run Code Online (Sandbox Code Playgroud)
但是,如果有超过2个实例,则可能不是您想要的.这有点粗糙,但你可以这样做来处理任意数量的事件:
int i = 1;
string output = Regex.Replace(input, @"title1", m => "title" + i++);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5933 次 |
| 最近记录: |