Replace double quotes (")

Here my line is as follows: -

sTest = AAAAA"1111 

I want to replace the double quote with a backslash and double quotes ( \" )

I need String Like

 sTest = AAAAA\"1111 
+4
source share
4 answers
 String escaped = "AAAAA\"1111".replace("\"", "\\\""); 

(Note that the replaceAll version handles regular expressions and is redundant for this particular situation.)

+3
source

string.replace("\"", "\\\"")

You want to replace " with \" . Since both " and \ have a certain meaning, you should avoid them correctly by adding the previous \ before each.

So "\" and \"\\\" . And since you want the compiler to understand that it is String, you need to wrap each line with double quotes So "\" and "\"""\\\"" .

+2
source

Although the other answers are correct for a specific situation, for more complex situations you can use StringEscapeUtils.escapeJava (String) from Apache Commons Lang.

 String escaped = StringEscapeUtils.escapeJava(string); 
+1
source
 System.out.println("AAAAA\"1111".replaceAll("\"", "\\\\\"")); 
0
source

All Articles