views:

105

answers:

6

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.
+3  A: 

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

string s = Regex.Replace(s, @"\bwest\b", "something");
Robert Harvey
Looks alright but this will ignore west, and west. And is it case insensitive?
Taz
I think it does the same as I am already doing Using 's=s.Replace(" West ","something");'
Taz
It works like string s = Regex.Replace(s, @"(\bwest\b)", "something");. And it works for west. and west, and west; as well. Dont really understand why :)
Taz
The "\b" matches a "word boundary". This regex is case sensitive, but you can add a RegexOptions.IgnoreCase (4th param) to make it case insensitive.
Hans Kesting
+3  A: 

Have you looked at Regex.Replace? Also, be sure to catch the return value; Replace (via any string mechanism) returns a new string - it doesn't do an in-place replace.

Marc Gravell
A: 

The String.Replace method can only replace substrings, but there is a Regex.replace method that does what you want: http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.replace.aspx

Hans Kesting
Please don't post old links.
John Saunders
It was the first link I found. I'll take care next time.
Hans Kesting
+2  A: 

Try using the System.Text.RegularExpressions.Regex class. It has a static Replace method. I'm not good with regular expressions, but something like

string outputText = Regex.Replace(inputText, "(\\sWest.\\s)", temp);

should work, if your regular expression is correct.

Peter
A: 

USe this code if you want it to be case insensitive

string pattern = @"\bwest\b";
string modifiedString = Regex.Replace(input, pattern, strReplacement, RegexOptions.IgnoreCase);
Archie
A: 

I agree with Robert Harvey's solution except for one small modification:

s = Regex.Replace(s, @"\bwest\b", "something", RegexOptions.IgnoreCase);

This will replace both "West" and "west" with your new word