问题描述
Java 中的以下代码片段:
The following code fragment in Java:
"\\\\".replaceAll("\\\\", "\\");
抛出异常:
java.lang.StringIndexOutOfBoundsException: String index out of range: 1 (NO_SOURCE_FILE:0)
javadoc on replaceAll 确实包含关于使用反斜杠的警告,并建议使用 Matcher.replaceAll 或 Matcher.quoteReplacement.有人有关于如何用单个反斜杠替换字符串中所有出现的两个反斜杠的片段吗?
The javadoc on replaceAll does include a caveat on the use of backslashes and recommends using Matcher.replaceAll or Matcher.quoteReplacement. Does anybody have a snippet on how to replace all occurrences of two backslashes in a string with a single backslash ?
上面显示的实际文字只是一个例子,实际的字符串可以在不同的地方多次出现两个连续的反斜杠.
The actual literal shown above is only an example, the actually string can have many occurrences of two consecutive backslashes in different places.
推荐答案
你可以用 String#replace()
:-
You can simply do it with String#replace()
: -
"\\\\".replace("\\\\", "\\")
String#replaceAll
接受一个 regex
作为参数.因此,您必须将 反斜杠
转义两次.一次用于 Java
,然后用于 Regex
.因此,使用 replaceAll
的实际替换看起来像:-
String#replaceAll
takes a regex
as parameter. So, you would have to escape the backslash
twice. Once for Java
and then for Regex
. So, the actual replacement using replaceAll
would look like: -
"\\\\".replaceAll("\\\\\\\\", "\\\\")
但您在这里并不真正需要 replaceAll
.
But you don't really need a replaceAll
here.
这篇关于“\\\\".replaceAll(“\\\\", “\\") 抛出 java.lang.StringIndexOutOfBoundsException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!