19

I have a statement:

I have a string such as

content = "*   test    *"

I want to search and replace it with so when I am done the string contains this:

content = "(*)   test    (*)"

My code is:

content = Regex.Replace(content, "*", "(*)");

But this causes an error in C# because it thinks that the * is part of the Regular Expressions Syntax.

How can I modify this code so it changes all asterisks in my string to (*) instead without causing a runtime error?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
fraXis
  • 3,141
  • 8
  • 44
  • 53

5 Answers5

38

Since * is a regex metacharacter, when you need it as a literal asterisk outside of a character class definition, it needs to be escaped with \ to \*.

In C#, you can write this as "\\*" or @"\*".

C# should also have a general purpose "quoting" method so that you can quote an arbitrary string and match it as a literal.

See also

Community
  • 1
  • 1
polygenelubricants
  • 376,812
  • 128
  • 561
  • 623
13

You can escape it:

\*

Benjamin Podszun
  • 9,679
  • 3
  • 34
  • 45
  • Also, consider using a tool if you are composing regular expressions. Expresso has helped me a lot: http://www.ultrapico.com/Expresso.htm – Thomas May 10 '10 at 09:52
10

You don't need a regular expression in this simple scenario. You can use String.Replace:

content = content.Replace("*", "(*)");
Kobi
  • 135,331
  • 41
  • 252
  • 292
5

Use Regex.Escape() It will take all of the string and make it into something you can use as part of a regex.

Cine
  • 4,255
  • 26
  • 46
4

Use \\* instead of * in regex.replace call

Midhat
  • 17,454
  • 22
  • 87
  • 114