fraXis
fraXis

Reputation: 3221

How do I replace an actual asterisk character (*) in a Regex expression?

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?

Upvotes: 19

Views: 67696

Answers (5)

Cine
Cine

Reputation: 4402

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

Upvotes: 5

Kobi
Kobi

Reputation: 138037

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

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

Upvotes: 10

polygenelubricants
polygenelubricants

Reputation: 383776

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

Upvotes: 39

Benjamin Podszun
Benjamin Podszun

Reputation: 9827

You can escape it:

\*

Upvotes: 13

Midhat
Midhat

Reputation: 17810

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

Upvotes: 5

Related Questions