我有两个字符串
string One="This is StackOverFlow, Thisis StackOverFlow, Thisis";
string Two="Hello HelloHello Hello This is StackOverFlow!"
我想将每个单独的 替换为 Hello Everyone In for string One,
每个单独的 Hello 到 Hello Everyone In for string Two
我用这种方式尝试:
One.Replace("This is","Hello Everyone In");
Output: Hello Everyone In StackOverFlow, Thisis StackOverFlow, Thisis
Two.Replace("Hello", "Hello Everyone In")
Output: Hello Everyone In Hello Everyone InHello Everyone In Hello Everyone In This is StackOverFlow!
正如您所看到的,我想用给定的字符串替换Hello,但它也替换了HelloHello,而HelloHello对于我的程序来说是不同的值,因此它必须是原始形式。
在字符串One中, Thisis 被视为不同字符串,但为什么在字符串2中考虑 HelloHello as Hello 重复
任何人都可以有解决方案吗?
抱歉我的英文不好
答案 0 :(得分:2)
你必须确保检查确切的单词。 \b
确保您只查看完全匹配而不是不同单词的匹配。正如docs解释一样:
匹配必须发生在\ w(字母数字)和a之间的边界上 \ W(非字母数字)字符。
这样的事情对你有用:
string yourInputString = "Hello HelloHello Hello This is StackOverFlow!";
string wordYouWantToReplace = @"\bHello\b";
string replaceWordTo = "Hello Everyone In";
string result = Regex.Replace(yourInputString, wordYouWantToReplace, replaceWordTo, RegexOptions.None);
如果您愿意,可以使用单独的方法自动将\b
标记添加到字符串中:
private string AddEscapeTags(string wordYouWantToReplace)
{
return string.Format(@"\b{0}\b", wordYouWantToReplace);
}
然后你可以拨打string yourInputString = AddEscapeTags("Hello");