Marquinio
Marquinio

Reputation: 4821

Escape Java RegExp Metacharacters

I'm trying to escape a RegExp metacharacter in Java. Below is what I want:

INPUT STRING: "This is $ test"
OUTPUT STRING: "This is \$ test"

This is what I'm currently doing but it's not working:

String inputStr= "This is $ test";
inputStr = inputStr.replaceAll("$","\\$");

But I'm getting wrong output:

"This is $ test$"

Upvotes: 2

Views: 1389

Answers (4)

pb2q
pb2q

Reputation: 59617

You'll need:

inputStr.replaceAll("\\$", "\\\\\\$");

The String to be replaced needs 2 backslashes because $ has a special meaning in the regexp. So $ must be escaped, to get: \$, and that backslash must itself be escaped within the java String: "\\$".

The replacement string needs 6 backslashes because both \ and $ have special meaning in the replacement strings:

  • \ can be used to escape characters in the replacement string.
  • $ can be used to make back-references in the replacement string.

So if your intended replacement string is "\$", you need to escape each of those two characters to get: \\\$, and then each backslash you need to use - 3 of them, 1 literal and 2 for escapes - must also be escaped within the java String: "\\\\\\$".

See: Matcher.replaceAll

Upvotes: 3

Ed Morales
Ed Morales

Reputation: 1037

You have to put 6 backslashes so you escape the backslash and escape the metachar:

inputStr.replaceAll("\\$","\\\\\\$");

Upvotes: 1

blacelle
blacelle

Reputation: 2217

As you said, $ is a reserved character for Regex. Then, you need to escape it. You can use a backslash character to do this:

inputStr.replaceAll("\\$", ...);

In the replacement, the $ and \ characters also have a special meaning:

Note that backslashes () and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string; see Matcher.replaceAll

Then, the replacement will be the backslash character and the dollar sign, both of them being escaped by a '\' character (which needs to be doubled toi build the String):

inputStr.replaceAll("\\$", "\\\\\\$");

Upvotes: 1

Edvin Syse
Edvin Syse

Reputation: 7297

The first argument to replaceAll is infact a regexp, and the $ actually means "match the end of the string". You can just use replace instead, which doesn't use regexp, just a normal string replace, to achieve what you want in this case. If you want to use a regexp, just escape the $ in the first argument.

Upvotes: 0

Related Questions