String.replace具有双反斜杠的所有单个反斜杠 [英] String.replaceAll single backslashes with double backslashes
问题描述
我正在尝试将 String
\something\
转换为字符串
\\something\\
使用 replaceAll
,但我不断得到各种错误。我以为这是解决方案:
I'm trying to convert the String
\something\
into the String
\\something\\
using replaceAll
, but I keep getting all kinds of errors. I thought this was the solution:
theString.replaceAll("\\", "\\\\");
但这给出了以下异常:
java.util.regex.PatternSyntaxException: Unexpected internal error near index 1
推荐答案
String#replaceAll()
将参数解释为,//docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html#sumrel =noreferrer>。 c $ c> \ 是 String
和正则表达式
。您需要双重转义为正则表达式:
The String#replaceAll()
interprets the argument as a regular expression. The \
is an escape character in both String
and regex
. You need to double-escape it for regex:
string.replaceAll("\\\\", "\\\\\\\\");
但是,您不一定需要正则表达式,只因为您需要一个确切的字符,字符替换,你不需要这里的模式。所以 String#replace()
应该足够了:
But you don't necessarily need regex for this, simply because you want an exact character-by-character replacement and you don't need patterns here. So String#replace()
should suffice:
string.replace("\\", "\\\\");
更新:as根据注释,您似乎希望在JavaScript上下文中使用该字符串。你可能会更好地使用 StringEscapeUtils#escapeEcmaScript()
,以覆盖更多字符。
Update: as per the comments, you appear to want to use the string in JavaScript context. You'd perhaps better use StringEscapeUtils#escapeEcmaScript()
instead to cover more characters.
这篇关于String.replace具有双反斜杠的所有单个反斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!