如何替换字符串中特定字符串的出现?
我有一个字符串,其中可能包含两次“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" }
我知道我们可以在这里使用Regex但是我无法在第二个实例上获得替换。 任何人都可以帮我一把吗?
这只会在第一个之后替换title1
的第二个实例(以及任何后续实例):
string output = Regex.Replace(input, @"(?<=title1.*)title1", "title2");
但是,如果有超过2个实例,则可能不是您想要的。 这有点粗糙,但你可以这样做来处理任意数量的事件:
int i = 1; string output = Regex.Replace(input, @"title1", m => "title" + i++);
您可以指定计数,以及开始搜索的索引
string str = @"server/api/shows?title1=its always sunny in philadelphia&title1=breaking bad ..."; Regex regex = new Regex(@"title1"); str = regex.Replace(str, "title2", 1, str.IndexOf("title1") + 6);
您也许可以使用负向前瞻:
title1(?!.*title1)
并替换为title2
。
看看它是如何在这里工作的。
这是我为类似任务创建的C#扩展方法,可以派上用场。
internal static class ExtensionClass { public static string ReplaceNthOccurance(this string obj, string find, string replace, int nthOccurance) { if (nthOccurance > 0) { MatchCollection matchCollection = Regex.Matches(obj, Regex.Escape(find)); if (matchCollection.Count >= nthOccurance) { Match match = matchCollection[nthOccurance - 1]; return obj.Remove(match.Index, match.Length).Insert(match.Index, replace); } } return obj; } }
然后您可以使用以下示例。
"computer, user, workstation, description".ReplaceNthOccurance(",", ", and", 3)
这会产生以下结果。
"computer, user, workstation, and description"
要么
"computer, user, workstation, description".ReplaceNthOccurance(",", " or", 1).ReplaceNthOccurance(",", " and", 2)
将产生以下。
"computer or user, workstation and description"
我希望这可以帮助那些有同样问题的人。
我在谷歌搜索中立即发现了这个链接。
C# – indexOf第n次出现的字符串?
获取IndexOf第一次出现的字符串。
使用返回的IndexOf的startIndex +1作为第二个IndexOf的起始位置。
在“1”字符的适当索引处将其子串到两个字符串中。
Concat它与“2”字符一起返回。
PSWG的做法非常棒。 但是在下面我提到了一个简单的方法来为那些在lambda和regex表达式中遇到问题的人完成它。;)
int index = input.LastIndexOf(“title1 =”);
string output4 = input.Substring(0,index – 1)+“&title2”+ input.Substring(index +“title1”.Length,input.Length – index – “title1”.Length);
你可以使用正则表达式替换MatchEvaluator
并给它一个“状态”:
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; });
通过使用后缀++
运算符(非常难以理解),替换可以是一行的。
string callingUrl2 = Regex.Replace(callingURL, "title1=", x => found++ == 1 ? "title2=" : x.Value);