how to replace ' \' with '/' in a java string [duplicate]

i have generated a file name and stored in a String variable path hav tried using

path=path.replaceAll('\','/') 

but this does not work

10

7 Answers

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);
4

If it is a file path, you should try "File.separator" instead of '\' (in case your application works with Nix platform)

5

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 "\".

5

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.

2

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("\\\\", "/");
8
 String s="m/j/"; String strep="\\\\"; String result=s.replaceAll("/", strep); System.out.println(result);
2

You Might Also Like