Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.
like image 494
Tasawer Khan Avatar asked May 05 '10 06:05

Tasawer Khan


People also ask

Can I use regex in replace?

How to use RegEx with . replace in JavaScript. To use RegEx, the first argument of replace will be replaced with regex syntax, for example /regex/ . This syntax serves as a pattern where any parts of the string that match it will be replaced with the new substring.

Does regex work only with strings?

So, yes, regular expressions really only apply to strings. If you want a more complicated FSM, then it's possible to write one, but not using your local regex engine.

Is regex faster than string replace?

String operations will always be faster than regular expression operations.

How do you replace a section of a string in regex?

The \[[^\]]*]\[ matches [ , then any 0+ chars other than ] and then ][ . The (...) forms a capturing group #1, it will remember the value that you will be able to get into the replacement with $1 backreference. [^\]]* matches 0+ chars other than ] and this will be replaced.


2 Answers

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"); 
like image 99
Robert Harvey Avatar answered Oct 13 '22 17:10

Robert Harvey


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.

like image 21
dortique Avatar answered Oct 13 '22 19:10

dortique