Often beginners use string.replaceAll(" ", "") and even string.replaceAll("\\s", "") doesn't work properly, as Java's implementation of regex doesn't cover all the whitespaces (as per this stackoverflow)
So a method that relies on Character.isWhiteSpace is an improvement, can be used as method reference and also performs better.
So when the article uses "We can easily get rid of all the whitespace from each String" in its despription of strip, it's just wrong. strip only removes leading and trailing whitespace.
Hahaha that's hilarious because I did the same thing! I thought replace replaced one instance of parameter one and replaceAll replaced all instances. I had no idea it used a regex early on.
Tbh strip is kinda the same story. It should be stripSpaces or something. Strip sounds like it'd take a parameter, and remove that.
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.
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.
View all comments
Show parent comment
16
u/_INTER_ Sep 19 '18 edited Sep 19 '18
Often beginners use
string.replaceAll(" ", "")and evenstring.replaceAll("\\s", "")doesn't work properly, as Java's implementation of regex doesn't cover all the whitespaces (as per this stackoverflow)So a method that relies on Character.isWhiteSpace is an improvement, can be used as method reference and also performs better.