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...
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)
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.
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.
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
. UseMatcher.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")));
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With