0

I have a string like this:

Durham * versus Yorkshire

and I have used a regex in C# to replace that asterisk in the string with some text, as:

string aString = "Durham * versus Yorkshire";
string newstring = Regex.Replace( aString, @"\*", "Replaced text");

I want this output:

Durham Replaced Text versus Yorkshire

but this is not working. I thought that escaping the * with a \ will find it. But its not. You can test it here as well: RegExr. Can somebody tell me where am I wrong?

Preetesh
  • 524
  • 8
  • 19

3 Answers3

3

For a simple replace like this one you don't need to use regex, String.Replace will be enough:

string aString = "Durham * versus Yorkshire";
string newstring = aString.Replace("*", "Replaced text");
Robin
  • 9,415
  • 3
  • 34
  • 45
  • I need to do it using regex. I have told this above. Anyways I have marked the answer. Thanks for helping. – Preetesh May 06 '14 at 07:53
3

Tried your code and it seemed to work. Even your regex works on regexr.com

string aString = "Durham * versus * Yorkshire";
string newstring = Regex.Replace(aString, @"\*", "Replaced text");

Output

Durham Replaced text versus Replaced text Yorkshire

You could also consider using String.Replace() like

aString.Replace("*", "Replaced text");
Yasser Shaikh
  • 46,934
  • 46
  • 204
  • 281
  • Damn! I was displaying the old string in the output field. Fixed it and now its working. My bad. Thanks. – Preetesh May 06 '14 at 07:51
0
string aString = "Durham * versus Yorkshire";
string newstring = Regex.Replace( aString, "\\*", "Replaced text");
Haseeb Asif
  • 1,766
  • 2
  • 23
  • 41
  • 1
    http://stackoverflow.com/questions/3311988/what-is-the-difference-between-a-regular-string-and-a-verbatim-string – Robin May 06 '14 at 07:36