• Post Reply Bookmark Topic Watch Topic
  • New Topic

String replaceAll Function  RSS feed

 
Sagar Yerunkar
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a String bo"ttle created using

String a = new String("bo\"ttle");

I want to replace the double quotes in the string with \" so that I get the output as bo\"ttle . I used the following function to do the same.

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

But the String does not change and I still get the output as bo"ttle.

However, when I use the funtion:

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

The output is bo\"ttle

Can somebody explain why the extra "\\" are required in this case?
 
Srikanth Ramu
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
a = a.replaceAll("\"","\\\\\"");

(or)

a = a.replaceAll("\"", "\\\\" + "\"");
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Sagar Yerunkar:
a = a.replaceAll("\"","\\\"");


The backslash is a special character that needs to be escaped for both the Java compiler *and* the regex engine.

That is, the compiler transforms "\\\"" to the String \\", for the regex engine that is an escaped backslash and a quote, making it to \". So you are replacing \" with \"

Does that sound reasonable?
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!