Tom Gullen
Tom Gullen

Reputation: 61729

Regex match backslash star

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!

Upvotes: 7

Views: 9457

Answers (3)

porges
porges

Reputation: 30580

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

Upvotes: 4

Guffa
Guffa

Reputation: 700152

Your syntax is completely wrong. It looks more like Javascript than C#.

This works fine:

string Text = "asdf*sadf";

Text = Regex.Replace(Text, "\\*", "[MULTIPLY]");

Console.WriteLine(Text);

Output:

asdf[MULTIPLY]sadf

To match \* you would use the pattern "\\\\\\*".

Upvotes: 0

Tim Pietzcker
Tim Pietzcker

Reputation: 336098

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

Upvotes: 11

Related Questions