Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape double quotes in Java [duplicate]

Tags:

java

escaping

People also ask

How do you escape a double quote in Java?

Double quotes characters can be escaped with backslash( \ ) in java.

How do you remove double quotes from a replacement string?

Use the String. replaceAll() method to remove all double quotes from a string, e.g. str. replaceAll('"', '') . The replace() method will return a new string with all double quotes removed.

How do you replace quotation marks in Java?

Just a character-by-character replace is sufficient. You can use String#replace() for this. String replaced = original. replace("\"", " ");

How do you match double quotes in Java?

If you are dealing with a char then simply do this: c == '"'; If c is equal to the double quote the expression will evaluate to true .


Use Java's replaceAll(String regex, String replacement)

For example, Use a substitution char for the quotes and then replace that char with \"

String newstring = String.replaceAll("%","\"");

or replace all instances of \" with \\\"

String newstring = String.replaceAll("\"","\\\"");

Escaping the double quotes with backslashes is the only way to do this in Java.

Some IDEs around such as IntelliJ IDEA do this escaping automatically when pasting such a String into a String literal (i.e. between the double quotes surrounding a java String literal)

One other option would be to put the String into some kind of text file that you would then read at runtime


For a String constant you have no choice other than escaping via backslash.

Maybe you find the MyBatis project interesting. It is a thin layer over JDBC where you can externalize your SQL queries in XML configuration files without the need to escape double quotes.