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)
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("\\$", "\\\\\\$");

```