0

所以我正在查看一些遗留代码并找到他们这样做的实例:

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

暂时忽略.matches(..)调用每次都会创建一个新的模式和匹配器(uhg) - 但有什么理由不将此行更改为:

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

如果字符串都是空格,我很确定正则表达式只是匹配。StringUtils 会捕获与第一个相同的条件吗?

4

3 回答 3

4

是的,StringUtils.isBlank(..)会做同样的事情,而且是更好的方法。看一下代码:

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;
}
于 2010-11-16T22:25:40.640 回答
1

如果字符串是更多零个或更多空白字符,则您是正确的正则表达式测试。

不使用正则表达式的好处

  • 正则表达式对许多人来说是神秘的,这使得它的可读性降低
  • 正如您正确指出.matches()的那样,开销不小
于 2010-11-16T22:52:11.970 回答
0
 /**
 * 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());
}
于 2013-07-08T14:44:15.610 回答