Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I replace \ with / in Java?

Tags:

java

regex

I tried with following regex, but it didn't work.

myString.replaceAll("\", "/");

Exception:

java.util.regex.PatternSyntaxException: Unexpected internal error near index 1 \ ^ at java.util.regex.Pattern.error(Unknown Source) at java.util.regex.Pattern.compile(Unknown Source) at java.util.regex.Pattern.(Unknown Source) at java.util.regex.Pattern.compile(Unknown Source) at java.lang.String.replaceAll(Unknown Source)

like image 441
newbie Avatar asked Dec 03 '25 09:12

newbie


1 Answers

Your code should not even compile.

"\" escapes the " so that the string continues. Writing String h = "\"hello\""; makes the string h contain "hello".

If we change then change it to it to "\\" (escaping the backslash) we run into another problem. The regular expression then tries to escape the next character. For example writing "\\d+" is a valid regular expression (matching digits).


In you case however you do not need regular expressions at all. Just use the replace(char, char) method of the string, it replaces all characters.

myString.replace('\\', '/');

By the way, if you are replacing paths, you should look at File.separator to get the systems path separator character.

like image 120
dacwe Avatar answered Dec 05 '25 21:12

dacwe



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!