I want to replace " in my string to \\" for later use by Javascript JSON.parse(...), I try the following test
String name = "\"ab\"c";
System.out.println("name before escape="+name);
String name1 = name.replaceAll("\"", "\\\"");
System.out.println("name1="+name1);
String name2 = name.replaceAll("\"", "\\\\\"");
System.out.println("name2="+name2);
String name3 = name.replaceAll("\"", "\\\\\\\"");
System.out.println("name3="+name3);
and result as follow:
name before escape="ab"c
name1="ab"c
name2=\"ab\"c
name3=\"ab\"c
so all fail, and I don't understand the output result
[Update1}
for question 2, I found the following work
System.out.println("name4=" + name.replaceAll("\"", Matcher.quoteReplacement("\\\\\"")));
Although I feel lost for the reason it works...
It's better to use replace()
instead of replaceAll()
:
String name = "\"ab\"c";
System.out.println("name before escape=" + name);
System.out.println("name1=" + name.replace("\"", "\\\\\""));
Output:
name before escape="ab"c
name1=\\"ab\\"c
Don't use replaceAll
, use replace
: name.replace("\"", "\\\"");
The reason is that replaceAll
uses regex and it can mess all your formatting up.
class Main {
public static void main(String[] args) {
String name = "\"ab\"c";
String name1 = name.replace("\"", "\\\\\"");
System.out.println(name1); // Prints: \\"ab\\"c
}
}
use replaceAll need to escape \ and "
String name = "\"ab\"c";
System.out.println("name before escape="+name);
String name1 = name.replaceAll("\\\"", "\\\\\\\\\"");
System.out.println("name1="+name1);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.