Why do I need to use four backstrokes to output one backstroke ?
String str = "\"";
str = 开发者_高级运维str.replaceAll("\"", "\\\\\"");
System.out.println(str);
returns \"
but
String str = str.replaceAll("\"", "\\\"");
System.out.println(str);
returns "
replaceAll
takes a regular expression for the first argument and a replacement string for the second - and you need to escape the backslash in the replacement string as well as in the Java code.
Unless you need regular expressions, just use String.replace
instead, which doesn't use regular expressions:
String text = "a\\b\\c";
System.out.println(text); // Prints a\b\c
String replaced = text.replace("\\", "x");
System.out.println(replaced); // Prints axbxc
Personally I think it was a bit of a mistake for String.replaceAll
to use regular expressions to start with (replacePattern
would at least have made it more obvious), but it's too late to change now...
The String treats \\
as \
, unfortunately regex does as well so you need \\\\
:|
精彩评论