Reputation: 512
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
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