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?
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.
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.
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.
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.
You can escape it:
\*
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With