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

java, regex

Solution

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

Problem

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

Original source

Related problems