I have a file name which is stored in a String variable path
.
I tried this:
path = path.replaceAll('\','/')
but it does not work.
I have a file name which is stored in a String variable path
.
I tried this:
path = path.replaceAll('\','/')
but it does not work.
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);
If it is a file path, you should try "File.separator" instead of '\' (in case your application works with Nix platform)
Your path=path.replaceAll('\','/');
will not compile, because you have to escape the backslash,
use path=path.replace('\\','/');
(it will replace all Occrurences, see JavaDoc)
or path=path.replaceAll("\\\\", "/");
(this regex escapes the backslash) ;-)
In the comments there is an explanation, why you need 4 of "\" to make the correct regex for one "\".
You should use the replace
method and escape the backslash:
path = path.replace('\\', '/');
See documentation:
public String replace(char oldChar, char newChar)
Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
As it is a file path you have absolutely no need whatsoever to do this operation at all. Java understands both syntaxes. If you are trying to convert a File to a URL or URI, it has methods to do that.
the \
is not just some character in java.
it has its significance, some characters when preceeded by \
have a special meaning,
refer here section escape sequence
for details
Thus if you want to use just \
in your code, there is an implementation \\
for it.
So replace
path=path.replaceAll("\","/")
with
path=path.replaceAll("\\","/")
And this will fail during execution giving you a PatternSyntaxException
, because the first String is a regular expression So based on @jlordo answer , this is the way to go
path = path.replaceAll("\\\\", "/");
String s="m/j/";
String strep="\\\\";
String result=s.replaceAll("/", strep);
System.out.println(result);