Java : Replace \" with " and \/ with /

hqt picture hqt · Nov 17, 2014 · Viewed 7.7k times · Source

I'm creating json string to send to the server. I use GSon to generate json string. Because my server doesn't understand string like: \"key\":value but "key":value or "a\/b" but a/b. So after generating json string, I use replaceAll method to fix this:

String res = original.replaceAll("\\/", "/").replaceAll("\\"", "\"");

But this method doesn't work as I expected. Please tell me how to replace string to conform with server as above.

Thanks :)

Answer

sp00m picture sp00m · Nov 17, 2014
  1. What you want to match: \"
  2. A backslash is a regex special char (used to escape), so you need to escape them: \\"
  3. A backslash is also a Java special char in strings (also used to escape), so you need to escape them: \\\\"
  4. a double-quote needs to be escaped as well in Java (since it's the string literal delimiter): \\\\\"

You want to replace by a double-quote, so the point #4 needs to be applied again:

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

Same logic for the other replacement (without the point #4 since no double-quote):

.replaceAll("\\\\/", "/")

Combined into one single regex:

.replaceAll("\\\\([\"/])", "$1")