Question: 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$"

```

Answer: 
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](http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#replaceAll%28java.lang.String,%20java.lang.String%29)
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.