I'm trying to replace the beginning of a string with backslashes to something else. For some weird reason the replaceAll function doesn't like backslashes.
String jarPath = "\\\\xyz\\abc\\wtf\\lame\\";
jarPath = jarPath.replaceAll("\\\\xyz\\abc", "z:");
What should I do to solve this issue.
Thank you.
You need to double each backslash (again) as the Pattern class that is used by replaceAll() treats it as a special character:
String jarPath = "\\\\xyz\\abc\\wtf\\lame\\";
jarPath = jarPath.replaceAll("\\\\\\\\xyz\\\\abc", "z:");
A Java string treats backslash as an escape character so what replaceAll sees is: \\\\xyz\\abc. But replaceAll also treats backslash as an escape character so the regular expression becomes the characters: \ \ x y z \ a b c
Its doesn't like it because \ is the escape character in C like languages (even as an escape on this forum) Which makes it a poor choice for a file seperator but its a change they introduced in MS-DOS...
The problem you have is that you have escape the \ twice so \\host\path becomes \\\\host\\path in the string but for the regex has to be escaped again :P \\\\\\\\host\\\\path
If you can use a forward slash this is much simpler
String jarPath = "//xyz/abc/wtf/lame/";
jarPath = jarPath.replaceAll("//xyz/abc", "z:");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With