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

Ankur picture Ankur · Jul 14, 2010 · Viewed 170.4k times · Source

I want to check that Java String or character array is not just made up of whitespaces, using Java?

This is a very similar question except it's Javascript:
How can I check if string contains characters & whitespace, not just whitespace?

EDIT: I removed the bit about alphanumeric characters, so it makes more sense.

Answer

Carl Smotricz picture Carl Smotricz · Jul 14, 2010

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.