Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - replace all instances of path separators with system path separator

Tags:

java

regex

I've taken the regex matching both slash and backslash from this answer: Regex to match both slash in JAVA

    String path = "C:\\system/properties\\\\all//";
    String replaced = path.replaceAll("[/\\\\]+", 
        System.getProperty("file.separator"));

However, I get the error:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1

What is wrong with this regex? Removing + doesn't change anything, the error message is the same...

like image 281
Web Devie Avatar asked Jul 23 '13 15:07

Web Devie


People also ask

What is path separator in Java?

Path Separator Windows and Unix systems use different conventions for the path separator (";" in Windows, ":" in Unix, ). Path separators are used to separate a list of paths, for example: (Windows) C:\Program Files\Java\jre6\bin;C:\MATLAB;C:\Some\Other\Path\bin; (Unix)

What is separatorChar?

separatorChar: Same as separator but it's char. File. pathSeparator: Platform dependent variable for path-separator. For example PATH or CLASSPATH variable list of paths separated by ':' in Unix systems and ';' in Windows system.

Why do we use separator in Java?

A file separator is a character that is used to separate directory names that make up a path to a particular location. This character is operating system specific.


2 Answers

It is documented in the Javadoc:

Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string; see Matcher.replaceAll. Use Matcher.quoteReplacement(java.lang.String) to suppress the special meaning of these characters, if desired.

So you can try this:

String replaced = path.replaceAll("[/\\\\]+", Matcher.quoteReplacement(System.
            getProperty("file.separator")));
like image 150
assylias Avatar answered Oct 28 '22 20:10

assylias


This should work:

String path = "C:\\system/properties\\\\all//";

Edit: modified following contents of assylias' answer

System.out.println(path.replaceAll("(\\\\+|/+)", Matcher.quoteReplacement(System.getProperty("file.separator"))));

End of edit

Output (for me - I use a mac):

C:/system/properties/all/

So it will "normalize" the double separators.

like image 21
Mena Avatar answered Oct 28 '22 20:10

Mena