Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 460
fraXis Avatar asked May 10 '10 09:05

fraXis


People also ask

What is the regex for asterisk?

The asterisk ( * ): The asterisk is known as a repeater symbol, meaning the preceding character can be found 0 or more times. For example, the regular expression ca*t will match the strings ct, cat, caat, caaat, etc.

How do you escape asterisk in regex?

You have to double-escape the backslashes because they need to be escaped in the string itself. The forward slashes mark the start and the end of the regexp. You have to start with a forward slash and end with one, and in between escape the asterisks with backslashes.

What does the * Do in regex?

This operator is similar to the match-zero-or-more operator except that it repeats the preceding regular expression at least once; see section The Match-zero-or-more Operator ( * ), for what it operates on, how some syntax bits affect it, and how Regex backtracks to match it.


2 Answers

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

  • Regular expressions and escaping special characters
    • Full list of what needs to be escaped, where/when
like image 187
polygenelubricants Avatar answered Sep 28 '22 07:09

polygenelubricants


You can escape it:

\*

like image 28
Benjamin Podszun Avatar answered Sep 28 '22 07:09

Benjamin Podszun