【问题标题】:StringUtils.isBlank vs. RegexpStringUtils.isBlank 与正则表达式
【发布时间】:2010-11-16 22:24:01
【问题描述】:

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

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

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

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

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

【问题讨论】:

    标签: java regex string apache-stringutils


    【解决方案1】:

    是的,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;
    }
    

    【讨论】:

      【解决方案2】:

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

      不使用正则表达式的好处

      • 正则表达式对许多人来说是晦涩难懂的,这使得它的可读性降低
      • 正如您正确指出的那样,.matches() 的开销并不小

      【讨论】:

        【解决方案3】:
         /**
         * 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());
        }
        

        【讨论】:

        • 这是不正确的。 OP 想知道字符串是否有空格或为空。 string.length() =&lt; 0 如果字符串为 ' ' 将返回 false 虽然这是一个空字符串并且应该在您的方法中返回 true,但它会返回 false,因为它既不是 null 也不是长度 =StringUtils.isBlank()(你应该这样做)你的 return 语句应该是 return (null == string) || (0 &gt;= string.trim().length()); .trim() 切断方法外部的所有空白区域。即:" hi hello ".trim() 相当于“hi hello”
        猜你喜欢
        • 2010-09-12
        • 2011-08-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-04
        • 2017-12-18
        • 2017-09-27
        相关资源
        最近更新 更多