Skip to main content

String replaceAll problem

3 replies [Last post]
Joined: 2005-10-13
Points: 0


I have string

<br />
String s = "Hello \"World\"";<br />

when i print this on console, it prints

Hello "World"

It works fine. Now what i want to is to print

<br />
Hello \"World\"

Which means i have to replace the quotes (") with (\\) and then a quote so that i may get a quote in output. so i used replaceAll method

System.out.println(s.replaceAll("\"", "\\\""));

But to my astonish, it prints out

Hello "World".

I wondered and then tried to do it again with

System.out.println(s.replaceAll("\"", "\\\\\""));

Now i was able to see the desired outout i.e; Hello \"World\"

But why i have to use 5 back slashes instead of 3 which were according to the logic of "backsequences"?? I have seen the replaceAll method and it is using the pattern matching in it.

If i try to replace the string using simple "replace" method it works fine; i.e i don't have to use 5 backslashes, i use only 3 (according to logic). Can someone explain why i have to use 5 slasheds in replaceAll.

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
Joined: 2005-01-28
Points: 0

replaceAll() uses regular expressions so you have one additional level of escaping. It can be a bit confusing since the escape char from regular expressions also is a backslash.

the replacement string you want is [b]\"[/b]

in the regular expression a \ must be escaped, so you must feed the method with [b]\\"[/b]

to get this in java, each \ must be input as \\ and the " as \" --> [b]\\\\\"[/b]


Joined: 2007-06-14
Points: 0

just in case, some nice plugins exist for Eclipse or IntelliJ to test your own regexp, very nice tools when u must play with regexp syntax :)

Joined: 2009-01-22
Points: 0

Write own method instead of String.replaceAll to your utility file.
Code is here


Binod Suman