How to replace ' \' with '/' in a Java string?
java, string
Solution
`replaceAll()` needs `Strings` as parameters. So, if you write
path = path.replaceAll('\', '/');
it fails because you should have written
path = path.replaceAll("\", "/");
But this also fails because character '\' should be typed '\\'.
path = path.replaceAll("\\", "/");
And this will fail during execution giving you a `PatternSyntaxException`, because the fisr `String` is a regular expression (Thanks @Bhavik Shah for pointing it out). So, writing it as a RegEx, as @jlordo gave in his answer:
path = path.replaceAll("\\\\", "/");
Is what you were looking for.
To make optimal your core, you should make it independent of the Operating System, so use @Thai Tran's tip:
path = path.replaceAll("\\\\", File.separator);
But this fails throwing an `StringIndexOutOfBoundsException` (I don't know why). It works if you use `replace()` with no regular expressions:
path = path.replace("\\", File.separator);
Problem
I have a file name which is stored in a String variable `path`. I tried this: ``` path = path.replaceAll('\','/') ``` but it does not work.