简体   繁体   English

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

[英]RegEx.Replace to Replace Whole Words and Skip when Part of the Word

I am using regex to replace certain keywords from a string (or Stringbuilder) with the ones that I choose. 我使用正则表达式将字符串(或Stringbuilder)中的某些关键字替换为我选择的关键字。 However, I fail to build a valid regex pattern to replace only whole words. 但是,我无法建立有效的正则表达式模式来仅替换整个单词。

For example, if I have InputString = "fox foxy" and want to replace "fox" with "dog" it the output would be "dog dogy". 例如,如果我有InputString =“ fox foxy”并想将“ fox”替换为“ dog”,则输出将是“ dog dogy”。

What is the valid RegEx pattern to take only "fox" and leave "foxy"? 仅接受“ fox”而保留“ foxy”的有效RegEx模式是什么?

 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;
        }

Thanks! 谢谢!

Regexes support a special escape sequence that represents a word boundary. 正则表达式支持代表单词边界的特殊转义序列。 Word-characters are everything in [a-zA-Z0-9] . 字字符是[a-zA-Z0-9] So a word-boundary is between any character that belongs in this group and a character that doesn't. 因此,单词边界位于该组中的任何字符与不属于该字符的字符之间。 The escape sequence is \\b : 转义顺序为\\b

\bfox\b

Do not forget to put '@' symbol before your '\\bword\\b'. 不要忘记在'\\ bword \\ b'之前加上'@'符号。 For example: 例如:

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

@ symbol ensures escape character, backslash(\\), does not get escaped! @符号确保转义字符反斜杠(\\)不会被转义!

您需要使用边界。

KeywordToReplace="\byourWord\b"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM