문제

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?

도움이 되었습니까?

해결책

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;
}

다른 팁

You are correct the regular expression test's if the string is more zero or more white space characters.

The advantages of not using the regular expression

  • Regular expressions are cryptic to many people, which makes it less readable
  • And as you rightly pointed out .matches() has a non trivial overhead
 /**
 * Returns if the specified string is <code>null</code> or the empty string.
 * @param string the string
 * @return <code>true</code> if the specified string is <code>null</code> or the empty string, <code>false</code> otherwise
 */
public static boolean isEmptyOrNull(String string)
{
    return (null == string) || (0 >= string.length());
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top