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

I accepted a regex matching both a slash and a backslash with this answer: Regex to match a slash in JAVA

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

However, I get the error message:

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

What is wrong with this regex? Removing + does not change anything, the error message is the same ...

+4
source share
2 answers

This is described in Javadoc :

Please note that the backslash (\) and dollar signs ($) in the replacement string may cause the results to differ from whether they are treated as a literal replacement string; see Matcher.replaceAll . Use Matcher.quoteReplacement(java.lang.String) to suppress the special meaning of these characters, if necessary.

So you can try the following:

 String replaced = path.replaceAll("[/\\\\]+", Matcher.quoteReplacement(System. getProperty("file.separator"))); 
+10
source

This should work:

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

Edit: changed contents of assylias response content

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

End of editing

Output (for me - I use mac):

 C:/system/properties/all/ 

Thus, it "normalizes" the double delimiters.

+1
source

Source: https://habr.com/ru/post/1492987/


All Articles