Naive
Naive

Reputation: 512

How to replace \" with empty value

I have a JSON string:

{
    "key1": "abc",
    "key2": "def",
    "key3": "gh\"i\"j"
}

Expected o/p:

{
    "key1": "abc",
    "key2": "def",
    "key3": "ghij"
}

Java string replace() and replaceAll() are replacing all double quotes:

System.out.println(a.replaceAll("\\\"",""));

System.out.println(a.replace("\"",""));

Output:

{
    key1: abc,
    key2: def,
    key3: ghij
}

The reason I'm trying to replace \" is that some operation has to be done using JSON, escaping special characters and storing the JSON string to a database. Here the json becomes invalid because of \".

How can I replace only \" with empty value?

Upvotes: 2

Views: 60

Answers (1)

Arnaud Denoyelle
Arnaud Denoyelle

Reputation: 31245

You want to replace \" with an empty string.

\ has a special meaning in regular expressions so you need to escape it. Hence, you need to replace \\" with an empty string.

Then, writing the string \\" in a string in java requires to escape each \ + the ".

Hence, the expression is \\ \\ \" (I added some spaces for readability):

Finally, you need to write it like this :

a.replaceAll("\\\\\"", "");

Upvotes: 1

Related Questions