Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: replaceAll doesn't work well with backslash?

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.

like image 873
thedp Avatar asked Dec 21 '25 05:12

thedp


2 Answers

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

like image 193
Adrian Pronk Avatar answered Dec 22 '25 19:12

Adrian Pronk


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:");
like image 31
Peter Lawrey Avatar answered Dec 22 '25 19:12

Peter Lawrey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!