简体   繁体   中英

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. 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".

What is the valid RegEx pattern to take only "fox" and leave "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;
        }

Thanks!

Regexes support a special escape sequence that represents a word boundary. Word-characters are everything in [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 :

\bfox\b

Do not forget to put '@' symbol before your '\\bword\\b'. For example:

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

@ symbol ensures escape character, backslash(\\), does not get escaped!

您需要使用边界。

KeywordToReplace="\byourWord\b"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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