Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java remove escaped double-quote

Tags:

java

regex

I have a long Java String that contains lots of escaped double-quotes:

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

I want to remove all the escaped double-quotes (\") and replace them with normal double-quotes (") so that I get:

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

I thought this was a no-brainer. My best attempt of:

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

Throws the following exception:

Unexpected internal error near index 1

Any ideas? Thanks in advance.

like image 441
IAmYourFaja Avatar asked Feb 14 '13 21:02

IAmYourFaja


3 Answers

Everybody is telling you to use replaceAll, the better answer is really to use replace.

replaceAll - requires regular expression

replace [javadoc]- is just a string search and replace

So like this:

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

Note that this is also faster because regular expression is not needed.

like image 151
Amir Raminfar Avatar answered Sep 30 '22 17:09

Amir Raminfar


Replace all uses Regular expressions, so add another set of \\

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

Explanation why: "\" is interpretad by java as a normal \. However if you would use only that in the parameter, it becomes the regular expression \. A \ in a regular expression escapes the next character. Since none is found, it throws an exception.

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

like image 37
Simon Forsberg Avatar answered Sep 30 '22 17:09

Simon Forsberg


  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."
like image 31
PermGenError Avatar answered Sep 30 '22 19:09

PermGenError