Search code examples
javareplaceall

java String replaceAll " to \\"


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

  1. why name2 and name3 are the same?
  2. how to replace all " to \\"

[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...


Solution

  • 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);