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

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