How do I check that a Java String is not all whitespaces?

Shortest solution I can think of:

if (string.trim().length() > 0) ...

This only checks for (non) white space. If you want to check for particular character classes, you need to use the mighty match() with a regexp such as:

if (string.matches(".*\\w.*")) ...

…which checks for at least one (ASCII) alphanumeric character.

Leave a Comment