45

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.
kame
  • 20,848
  • 33
  • 104
  • 159
Tasawer Khan
  • 5,994
  • 7
  • 46
  • 69

8 Answers8

68

No, but you can use the Regex class.

Code 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");
Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
39

Answer to the question is NO - you cannot use regexp in string.Replace.

If you want to use a regular expression, you must use the Regex class, as everyone stated in their answers.

dortique
  • 820
  • 8
  • 9
  • 9
    +1 only answer that directly answers the question if you can use String.Replace also for regex expressions – drkthng Oct 06 '15 at 09:37
9

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
  • 1,026,079
  • 266
  • 2,566
  • 2,900
4

Insert the regular expression in the code before class

using System.Text.RegularExpressions;

below is the code for string replace using regex

string input = "Dot > Not Perls";
// Use Regex.Replace to replace the pattern in the input.
string output = Regex.Replace(input, "some string", ">");

source : http://www.dotnetperls.com/regex-replace

Talha
  • 41
  • 7
4

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
  • 1,595
  • 13
  • 18
3

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
  • 2,564
  • 8
  • 39
  • 50
3

In Java, String#replace accepts strings in regex format but C# can do this as well using extensions:

public static string ReplaceX(this string text, string regex, string replacement) {
    return Regex.Replace(text, regex, replacement);
}

And use it like:

var text = "      space          more spaces  ";
text.Trim().ReplaceX(@"\s+", " "); // "space more spaces"
mr5
  • 3,438
  • 3
  • 40
  • 57
1

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

Kyllan
  • 103
  • 2
  • 10