开发者

Escaping a backstroke not working as expected

开发者 https://www.devze.com 2023-03-14 00:19 出处:网络
Why do I need to use four backstrokes to output one backstroke ? String str = \"\\\"\"; str = 开发者_高级运维str.replaceAll(\"\\\"\", \"\\\\\\\\\\\"\");

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 \\\\ :|

0

精彩评论

暂无评论...
验证码 换一张
取 消