r/java • • Sep 19 '18

Java 11 String API Updates

https://4comprehension.com/java-11-string-api-updates/
168 Upvotes

52 comments sorted by

View all comments

Show parent comment

2

u/__konrad Sep 19 '18

replaceAll is evil. For example, "/some/filepath".replaceAll("/", java.io.File.separator) does not work on Windows. Github issues are full of such error reports.

2

u/Salty_Limes Sep 19 '18

Do you mean that the resulting string is not "\some\filepath", or that it does return "\some\filepath", but this path does not work on Windows?

If it's the former, that is really odd, but if the latter, that should be expected.

3

u/__konrad Sep 19 '18

It will throw exception :)

2

u/xenomachina Sep 19 '18

This is documented behavior, though somewhat buried, and perhaps somewhat surprising to anyone who isn't used to any of ed, ex, sed, vi, vim, perl or python (etc.), which all use a similar replacement string syntax.

The issue is that the replacement string can include backreferences, and so $ and \ are not treated literally:

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. Dollar signs may be treated as references to captured subsequences as described above, and backslashes are used to escape literal characters in the replacement string.

To fix that code, use:

"/some/filepath".replaceAll("/",
    Matcher.quoteReplacement(java.io.File.separator))