问题
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$"
回答1:
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
回答2:
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("\\$", "\\\\\\$");
回答3:
You have to put 6 backslashes so you escape the backslash and escape the metachar:
inputStr.replaceAll("\\$","\\\\\\$");
回答4:
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.
来源:https://stackoverflow.com/questions/11041674/escape-java-regexp-metacharacters