How to properly trim whitespaces from a string in Java?

Viewed 22502
6 Answers

This handles Unicode characters and doesn't require extra libraries:

String trimmed = original.replaceAll ("^\\p{IsWhite_Space}+|\\p{IsWhite_Space}+$", "");

A slight snag is that there are some related whitespace characters without Unicode character property "WSpace=Y" which are listed in Wikipedia. These probably won't cause a problem, but you can easy add them to the character class too.

Using almson-regex the regex will look like:

String trimmed = original.replaceAll (either (START_BOUNDARY + oneOrMore (WHITESPACE), oneOrMore (WHITESPACE) + END BOUNDARY), "");

and include the more relevant of the non-Unicode whitespace.

Related