How can I find whitespace in a String?

For checking if a string contains whitespace use a Matcher and call its find method.

Pattern pattern = Pattern.compile("\\s");
Matcher matcher = pattern.matcher(s);
boolean found = matcher.find();

If you want to check if it only consists of whitespace then you can use String.matches:

boolean isWhitespace = s.matches("^\\s*$");

Leave a Comment