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

63,053

Solution 1

No, but you can use 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");

Solution 2

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.

Solution 3

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.

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

Solution 5

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"
Share:
63,053
Tasawer Khan
Author by

Tasawer Khan

I am a software developer. pph.me/maahir-systems

Updated on December 30, 2021

Comments

  • Tasawer Khan
    Tasawer Khan over 2 years

    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.