0

I am trying to replace " with \" in Java, but all the slashes are getting very confusing. What is the proper way to replace " with \" in Java?

string.replaceAll("\"","\\"");
Turing85
  • 13,364
  • 5
  • 27
  • 49
Alex Stone
  • 41,555
  • 51
  • 213
  • 379
  • 2
    `string.replaceAll("\"","\\\\\"");` – Avinash Raj Apr 22 '15 at 14:25
  • 5
    Why don't you just use a JSON library instead? Don't reinvent the wheel, probably badly... (This isn't a judgement on your coding abilities - just that unless your primary task is building a JSON library, you're unlikely to do as good a job of it as those whose primary task *is* building a JSON library.) – Jon Skeet Apr 22 '15 at 14:28
  • See also: http://stackoverflow.com/questions/3020094/how-should-i-escape-strings-in-json – Tim B Apr 22 '15 at 14:30

3 Answers3

5

If you are going to replace literals then don't use replaceAll but replace.

Reason for this is that replaceAll uses regex syntax which means that some characters will be treated specially like + * \ ( ) and to make them literals you will need to escape them. replace adds escaping mechanism for you automatically, so instead of

replaceAll("\"", "\\\\\"")

you can write

replace("\"", "\\\"");

which is little less confusing.

Pshemo
  • 113,402
  • 22
  • 170
  • 242
-1

Try to use char:

public void bsp(){
  //34 = " ; 92 = \
  String replace = "\"";
  String replace2 = "\\";
  text.replace(replace.charAt(0),replace2.charAt(0));
}
  • You should try this approach first before posting it as answer (hint: `char` can be also considered as integer). – Pshemo Apr 22 '15 at 15:03
-2
string.replaceAll("\"", "\\\"");

Let's explain: "\"" : is a string with \" an escaped " char "\\\"": is a string with a \\ an escaped \ char and a \" an escapd " char

karthik manchala
  • 13,025
  • 1
  • 27
  • 54
  • This will not work. ``\`` is also special character in replacement part so you also need to escape it there (just like in regex). – Pshemo Apr 22 '15 at 14:37