Skip to main content

APIzation: Replication Package

[Q#33260938][A#33261057] How can i replace double quotes with escape character in java?

https://stackoverflow.com/q/33260938

I have such text : How could i replace "" with " ? I tried like this : But i got "fullName":""Some full name". As you can see only second "" have been replaced by ".

Answer

https://stackoverflow.com/a/33261057

You should first replace " with " and then replace "" with ". You can do it by chaining a few String#replaceAll() calls: which will produce

APIzation

text = text.replaceAll("\\\"","\"").replaceAll("\"\"", "\"");
System.out.println(text);
"fullName":"Some full name"
package com.stackoverflow.api;

public class Human33261057 {

  public static String escapeDoubleQuotes(String text) {
    text = text.replaceAll("\\\"", "\"").replaceAll("\"\"", "\"");
    return text;
  }
}

package com.stackoverflow.api;

/**
 * How can i replace double quotes with escape character in java?
 *
 * @author APIzator
 * @see <a href="https://stackoverflow.com/a/33261057">https://stackoverflow.com/a/33261057</a>
 */
public class APIzator33261057 {

  public static String replaceQuote(String text) throws Exception {
    text = text.replaceAll("\\\"", "\"").replaceAll("\"\"", "\"");
    return text;
  }
}