How can I find whitespace in a String?

后端 未结 14 1061
感动是毒
感动是毒 2020-12-01 05:08

How can I check to see if a String contains a whitespace character, an empty space or \" \". If possible, please provide a Java example.

For example: String

14条回答
  •  醉话见心
    2020-12-01 05:50

    For checking if a string contains whitespace use a Matcher and call it's 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*$");
    

提交回复
热议问题