Ankur Ankur - 4 months ago 11
Java Question

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

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.


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.