转义Java RegExp元字符 [英] Escape Java RegExp Metacharacters
问题描述
我正在尝试转义Java中的RegExp元字符.以下是我想要的:
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$"
推荐答案
您需要:
inputStr.replaceAll("\\$", "\\\\\\$");
要替换的字符串需要2个反斜杠,因为 $ 在正则表达式中具有特殊含义.因此,必须对$进行转义,以获得: \ $
,并且必须在Java字符串中对反斜杠 self 进行转义:"\\ $"
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: "\\$"
.
替换字符串需要6个反斜杠,因为 \ 和 $ 在替换字符串中都有特殊含义:
The replacement string needs 6 backslashes because both \ and $ have special meaning in the replacement strings:
- \可用于转义替换字符串中的字符.
- $可用于在替换字符串中进行反向引用.
因此,如果您希望的替换字符串是"\ $",则需要对这两个字符进行转义以获取: \\\ $
,然后需要使用每个反斜杠-3个它们,即1个文字和2个用于转义的字符-必须也必须在Java字符串中进行转义:"\\\\\\ $"
.
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: "\\\\\\$"
.
请参阅: 查看全文