Reputation: 30284
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
Reputation: 48837
\"
\\"
\\\\"
\\\\\"
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
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
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