我有一个字符串,我想在其中替换整个单词。这就是我所拥有的:
var TheWord = "SomeWord";
TheWord = "\b" + TheWord + "\b";
TheText = TheText.replace(TheWord, "SomeOtherWord");
我正在使用"\b"
,因为我只想替换"SomeWord"
,而不是"SomeWordDifferent"
。文本如下所示:var TheHTML = '<div class="SomeWord">';
但是,替换不会发生。我需要改变什么?
答案 0 :(得分:5)
你需要逃避反斜杠。尝试其中任何一个......
TheWord = @"\b" + TheWord + @"\b";
或
TheWord = "\\b" + TheWord + "\\b";
答案 1 :(得分:0)
我假设您正在尝试使用正则表达式。方法是
string Regex.Replace(string input, string replacment)
所以我认为这就是你想要的:
string text = ...; // text comes from somewhere
string pattern = @"\bSomeWord\b"; // escape \b (word boundary regex anchor), or use verbatim string literal, like here
var regex = new Regex(pattern);
text = regex.Replace(text, "SomeOtherWord");
或者只是Tim写的Replace
方法的静态版本:
Regex.Replace(text, pattern, "SomeOtherWord");