Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex match backslash star

Tags:

regex

c#-4.0

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!

like image 347
Tom Gullen Avatar asked Aug 01 '11 10:08

Tom Gullen


People also ask

What does * do in regex?

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.

How do you match a backslash in regex?

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 ('\\').

What does * mean in regular expression?

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 a star 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.


2 Answers

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).

like image 113
Tim Pietzcker Avatar answered Oct 30 '22 18:10

Tim Pietzcker


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: @"\\\*".

like image 31
porges Avatar answered Oct 30 '22 16:10

porges