Search code examples
javaregexstringapache-stringutils

StringUtils.isBlank vs. Regexp


So I am looking through some legacy code and finding instance where they do this:

if ((name == null) || (name.matches("\\s*")))
   .. do something

Ignore for the moment that the .matches(..) call creates a new Pattern and Matcher everytime (uhg) - but is there any reason not to change this line to:

if (StringUtils.isBlank(name))
   ..do something

I'm pretty sure the regex simply matches if the string is all whitespace. Will StringUtils catch all the same conditions as the first one?


Solution

  • Yes, StringUtils.isBlank(..) will do the same thing, and is a better way to go. Take a look at the code:

    public static boolean isBlank(String str) {
         int strLen;
         if ((str == null) || ((strLen = str.length()) == 0))
             return true;
         int strLen;
         for (int i = 0; i < strLen; ++i) {
            if (!(Character.isWhitespace(str.charAt(i)))) {
               return false;
            }
         }
       return true;
    }