Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to safely replace single slash with double slash in Java, leaving existing double slash untouched?

I have a string which contain a directory path. Value of the string is set from some environment variable. The number of slashes in the string might vary like below (as in sysout).

String path = "C:\dirA\dirB\dirC"

or

String path = "C:\\dirA\\dirB\\dirC"

I am expecting \\ and not \. For this, I can try path.replace('\','\\') which converts first string to second one. But if the environment variable is already in the format of C:\\dirA\\dirB\\dirC, then path.replace() will give me C:\\\\dirA\\\\dirB\\\\dirC, and I dont want that. So how can I replace \ with \\ and leave the existing \\ in the string?

like image 888
Alfred Avatar asked Oct 25 '25 03:10

Alfred


1 Answers

You can use path.replaceAll('\\\\+','\\\\\\\\')

like image 141
Murat Karagöz Avatar answered Oct 26 '25 18:10

Murat Karagöz



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!