RegEx.Replace替换整个单词并在单词的一部分时跳过

时间:2012-10-03 14:57:32

标签: c# .net regex string

我正在使用正则表达式将字符串(或Stringbuilder)中的某些关键字替换为我选择的关键字。但是,我无法构建有效的正则表达式模式来仅替换整个单词。

例如,如果我有InputString =“fox foxy”并且想要用“dog”替换“fox”,那么输出将是“dog dogy”。

什么是有效的RegEx模式只能采取“狐狸”并留下“foxy”?

 public string Replace(string KeywordToReplace, string Replacement) /
        {

            this.Replacement = Replacement;
            this.KeywordToReplace = KeywordToReplace;

            Regex RegExHelper = new Regex(KeywordToReplace, RegexOptions.IgnoreCase);

            string Output = RegExHelper.Replace(InputString, Replacement);

            return Output;
        }

谢谢!

3 个答案:

答案 0 :(得分:6)

正则表达式支持表示单词边界的特殊转义序列。单词字符是[a-zA-Z0-9]中的所有内容。因此,字边界位于该组中属于的任何字符与不属于该字符的字符之间。转义序列为\b

\bfox\b

答案 1 :(得分:2)

不要忘记在'\ bword \ b'之前添加'@'符号。 例如:

address = Regex.Replace(address, @"\bNE\b", "Northeast");

@符号确保转义字符,反斜杠(\),不会被转义!

答案 2 :(得分:0)

你需要使用边界..

KeywordToReplace="\byourWord\b"