Skip to main content

String replaceAll problem

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

Hi,

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.
_simu_
Offline
Joined: 2005-01-28
Points: 0

Hi,
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]

ok?

darul75
Offline
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 :)

binodsuman
Offline
Joined: 2009-01-22
Points: 0

Write own method instead of String.replaceAll to your utility file.
Code is here http://binodjava.blogspot.com/2009/05/stringreplaceall-not-working-solut...

Thanks,

Binod Suman

http://binodsuman.blogspot.com