问题

我正在尝试将String``\something\转换为String``\\something\\使用replaceAll,但我一直遇到各种错误。我认为这是解决方案:

theString.replaceAll("\\", "\\\\");

但这给出了以下例外情况:

java.util.regex.PatternSyntaxException: Unexpected internal error near index 1

#1 热门回答(176 赞)

TheString#replaceAll()将参数解释为aregular expression。 The\的转义字符Stringregex。你需要双重逃避正则表达式:

string.replaceAll("\\\\", "\\\\\\\\");

但是你不一定需要正则表达式,因为你想要一个确切的逐字符替换,而你不需要这里的模式。 SoString#replace()应该足够了:

string.replace("\\", "\\\\");

更新:根据注释,你似乎希望在JavaScript上下文中使用该字符串。你可能最好使用720838581来覆盖更多角色。


#2 热门回答(13 赞)

为避免这种麻烦,你可以使用replace(采用普通字符串)代替replaceAll(采用正则表达式)。你仍然需要转义反斜杠,但不是以正则表达式所需的狂野方式。


#3 热门回答(7 赞)

你需要在第一个参数中转义(转义)反斜杠,因为它是一个正则表达式。替换(第二个参数 - 参见Matcher#replaceAll(String))也有反斜杠的特殊含义,所以你必须将它们替换为:

theString.replaceAll("\\\\", "\\\\\\\\");

原文链接