String replaceAll method removes backslashes in replacement string
Raja Kannappan
Ranch Hand
Joined: May 08, 2002
Posts: 83
posted
0
When I use String replaceAll() method, it removes all the backslashes in my replacement string. The matcher class in jdk explicity removes all the backslashes. Is there any way to avoid this?
when I do str.replaceAll("xyz", "c:\\temp\\xyz"); it replaces xyz with ctempxyz instead of c:\temp\xyz.
Does anyone know how to replace the string without replacing slashes? Any help is greatly appreciated. Thanks. [ February 15, 2008: Message edited by: Raja Kannappan ]
SCJP
Garrett Rowe
Ranch Hand
Joined: Jan 17, 2006
Posts: 1295
posted
0
You have to use four backslashes:
Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them. - Laurence J. Peter
Raja Kannappan
Ranch Hand
Joined: May 08, 2002
Posts: 83
posted
0
I tried that before and it worked, but I had problems converting my input replacement string (coming from user) to the desired format. Previously, I tried replacement = replacement.replaceAll("\\", "\\\\"); but it gave me error. Now, i tried replacement = replacement.replaceAll("\\\\", "\\\\\\\\"); and it works fine.
The problem is solved but I don't understand why we have to put four slashes. I understand that we put two back slashes instead of one backslash as a escape construct so that second backslash is actually taken as a character. But, I don't understand why we have to use four slashes. Can anyone please explain?
Thanks.
Garrett Rowe
Ranch Hand
Joined: Jan 17, 2006
Posts: 1295
posted
0
[Raja]:But, I don't understand why we have to use four slashes. Can anyone please explain?
Obviously a forward slash is a special character in a String, but a forward slash is also a special character in a regex. The forward slash has to be escaped with another forward slash in order for the regex engine to view it as a literal '\' character. Both forward slashes have to be escaped so that the String class views them as literal '\'. Therefore you end up needing four forward slashed.
Raja Kannappan
Ranch Hand
Joined: May 08, 2002
Posts: 83
posted
0
Thanks Garrett. That helps! [ February 17, 2008: Message edited by: Raja Kannappan ]