Can't work this one out, this matches a single star:
// Escaped multiply
Text = Text.replace(new RegExp("\\*", "g"), '[MULTIPLY]');
But I need it to match \*
, I've tried:
\\*
\\\\*
\\\\\*
Can't work it out, thanks for any help!
The Match-zero-or-more Operator ( * ) This operator repeats the smallest possible preceding regular expression as many times as necessary (including zero) to match the pattern. `*' represents this operator. For example, `o*' matches any string made up of zero or more `o' s.
The backslash suppresses the special meaning of the character it precedes, and turns it into an ordinary character. To insert a backslash into your regular expression pattern, use a double backslash ('\\').
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.
You were close, \\\\\\*
would have done it.
Better use verbatim strings, that makes it easier:
RegExp(@"\\\*", "g")
\\
matches a literal backslash (\\\\
in a normal string), \*
matches an asterisk (\\*
in a normal string).
Remember that there are two 'levels' of escaping.
First, you are escaping your strings for the C# compiler, and you are also escaping your strings for the Regex engine.
If you want to match "\*"
literally, then you need to escape both of these characters for the regex engine, since otherwise they mean something different. We escape these with backslashes, so you will have "\\\*"
.
Then, we have to escape the backslashes in order to write them as a literal string. This means replacing each backslash with two backslashes: "\\\\\\*"
.
Instead of this last part, we could use a "verbatim string", where no escapes are applied. In this case, you only need the result from the first escaping: @"\\\*"
.
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