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$"
You’ll need:
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:
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