hqt
hqt

Reputation: 30284

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

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

Upvotes: 3

Views: 9582

Answers (3)

sp00m
sp00m

Reputation: 48837

  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")

Upvotes: 9

SMA
SMA

Reputation: 37063

Try replace as below:

System.out.println("before " + json + " after " + json.replace("\\", ""));

Output is:

before String json = \"key\":valuea\/b"; after String json = "key":valuea/b";

Upvotes: 0

Tim Pietzcker
Tim Pietzcker

Reputation: 336378

Welcome to Java backslash hell:

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

In a regex, \\ matches a single \ character, and in a string (which you build the regex from), you need to write "\\" for every single literal "\", so you need four backslashes for each actual backslash you want to match by regex.

It would be nice if Java had either a literal regex type (like Ruby, Perl or JavaScript) or a verbatim string type (like C# or Python), but unfortunately, it doesn't.

Upvotes: 4

Related Questions