要用双反斜杠替换单个反斜杠需要八个反斜杠? [英] Eight backslashes required to replace single backslash with double backslashes?
问题描述
这是一个到底发生了什么"的问题.我实际上不需要解决方案.
This is a "what the heck is going on here" question. I don't actually need a solution.
我必须用双反斜杠替换字符串中的所有单反斜杠.这就是我最终要做的...
I had to replace all single backslashes in a String with double backslashes . This is what I ended up doing...
strRootDirectory = strRootDirectory.replaceAll("\\\\", "\\\\\\\\");
...其中strRootDirectory是上面的java.lang.String.
...where strRootDirectory is a java.lang.String above.
现在,我理解第一个参数的四个反斜杠:regex期望两个反斜杠以表示单个文字反斜杠,而Java希望它们加倍.很好.
Now, I understand the four backslashes for the first argument: regex expects two backslashes in order to indicate a single literal backslash, and java wants them doubled up. That's fine.
但是,第二个参数的八个反斜杠到底是怎么回事?替换字符串不应该是文字字符串(我是说非正则表达式)吗?我希望在第二个参数中需要四个反斜杠,以便表示两个反斜杠.
BUT, what the heck is going on with the eight backslashes for the second argument? Isn't the replacement string supposed to be a literal (non-regex, I mean) string? I expected to need four backslashes in the second argument, in order to represent two backslashes.
推荐答案
第二个参数不是regex-string,而是regex-replacement-string,其中反斜杠也具有特殊含义(用于转义用于变量插值的特殊字符 $
,也用于转义自身).
The second argument isn't a regex-string, but a regex-replacement-string, in which the backslash also has a special meaning (it is used to escape the special character $
used for variable interpolation and is also used to escape itself).
通过API:
请注意,替换字符串中的反斜杠(
\
)和美元符号($
)可能导致结果与被视为文字替换时的结果有所不同细绳;请参阅Matcher.replaceAll
.如果需要,可以使用Matcher.quoteReplacement(java.lang.String)
取消显示这些字符的特殊含义.
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; seeMatcher.replaceAll
. UseMatcher.quoteReplacement(java.lang.String)
to suppress the special meaning of these characters, if desired.
- 查看全文