Java removes hidden double quote

I have a long Java string containing many escaped double quotes:

// Prints: \"Hello my name is Sam.\" \"And I am a good boy.\" System.out.println(bigString); 

I want to remove all hidden double quotes ( \" ) and replace them with regular double quotes ( " ) to get:

 // Prints: "Hello my name is Sam." "And I am a good boy." System.out.println(bigString); 

I thought it wasn’t easy. My best attempt:

 bigString = bigString.replaceAll("\\", ""); 

Throws the following exception:

Unexpected internal error near index 1

Any ideas? Thanks in advance.

+4
source share
4 answers

Everyone tells you to use replaceAll , the best answer is to really use replace .

replaceAll - requires regular expression

replace [javadoc] is just a string search and replacement

So like this:

bigString = bigString.replace("\\\"", "\"");

Please note that this is also faster because a regular expression is not required.

+11
source

Replace all applications with Regular Expressions, so add another set \\

 bigString = bigString.replaceAll("\\\\\"", "\""); 

Explanation of why: "\" is interpreted by java as normal \ . However, if you use only this parameter, it becomes the regular expression \ . A \ in the regular expression goes beyond the next character. Since none were found, it throws an exception.

When you write in Java "\\\\\"" , it is first treated by java as a regular expression \\" . Which is then processed by the regex implementation as a backslash followed by a double quote.

+4
source
  String str="\"Hello my name is Sam.\" \"And I am a good boy.\""; System.out.println(str.replaceAll("\\\"", "\"")); 

Output:

  "Hello my name is Sam." "And I am a good boy." 
+1
source

The first argument to replaceAll is a regular expression. You pass \ which is not a valid regular expression. Try:

 bigString.replaceAll("\\\\", ""); 
0
source

All Articles