这是一个“这里到底发生了什么”的问题。我实际上不需要解决方案。
我不得不用双反斜杠替换字符串中的所有单反斜杠。这就是我最终做的......
strRootDirectory = strRootDirectory.replaceAll("\\\\", "\\\\\\\\");
...其中 strRootDirectory 是上面的 java.lang.String。
现在,我理解了第一个参数的四个反斜杠:regex 需要两个反斜杠来指示单个文字反斜杠,而 java 希望它们加倍。没关系。
但是,第二个参数的八个反斜杠到底是怎么回事?替换字符串不应该是文字(我的意思是非正则表达式)字符串吗?我预计在第二个参数中需要四个反斜杠,以表示两个反斜杠。
最佳答案
第二个参数不是regex-string,而是regex-replacement-string,其中反斜杠也有特殊含义(用于转义特殊字符$
用于变量插值,也用于逃逸自身)。
来自 API:
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.-- http://download.oracle.com/javase/6/docs/api/java/lang/String.html#replaceAll(...)
关于java - 用双反斜杠替换单反斜杠需要八个反斜杠吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7766765/