1

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!

3 Answers3

6

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
Martin Ender
  • 43,427
  • 11
  • 90
  • 130
2

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!

DevelopZen
  • 375
  • 4
  • 6
0

You need to use boundary..

KeywordToReplace="\byourWord\b"
Anirudha
  • 32,393
  • 7
  • 68
  • 89
  • The funny thing is that if I use it like that it works - "\bfox\b". But when I try to create the pattern separately like "string Pattern = "\b" + Keyword + "\b" and later use it Regex.Replace(Pattern, NewKeyword) it doesn't. – Georgiev Georgi Oct 03 '12 at 16:04
  • Found it, it's the "@" before "\b" but I really don't know what it does there. – Georgiev Georgi Oct 03 '12 at 16:09
  • @GeorgievGeorgi check out this [question](http://stackoverflow.com/questions/556133/whats-the-in-front-of-a-string-in-c) – Anirudha Oct 03 '12 at 16:12