Forums Register Login

String replaceAll Function

+Pie Number of slices to send: Send
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?
+Pie Number of slices to send: Send
a = a.replaceAll("\"","\\\\\"");

(or)

a = a.replaceAll("\"", "\\\\" + "\"");
+Pie Number of slices to send: Send
 

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?
Would you like to try a free sample? Today we are featuring tiny ads:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 936 times.
Similar Threads
Removing Characters from String
replacing string parts
how to replace colon (:) in a String
String.replaceAll
Formatting numbers with patterns
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 29, 2024 05:07:26.