Can I use regular expressions with String.Replace in C#?

Tasawer Khan picture Tasawer Khan · May 5, 2010 · Viewed 48.8k times · Source

For example I have code below string txt="I have strings like West, and West; and west, and Western."

I would like to replace the word west or West with some other word. But I would like not to replace West in Western.

  1. Can I use regular expression in string.replace? I used inputText.Replace("(\\sWest.\\s)",temp); It dos not work.

Answer

Robert Harvey picture Robert Harvey · May 5, 2010

To replace the whole word (rather than part of the word):

string s = "Go west Life is peaceful there";
s = Regex.Replace(s, @"\bwest\b", "something");