简体   繁体   English

StringUtils.isBlank与Regexp

[英]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: 暂时忽略.matches(..)调用每次都会创建一个新的Pattern and Matcher(uhg)-但是有任何理由不将此行更改为:

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? StringUtils会遇到与第一个相同的所有条件吗?

Yes, StringUtils.isBlank(..) will do the same thing, and is a better way to go. 是的, StringUtils.isBlank(..)将做同样的事情,并且是更好的方法。 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 正如您正确指出的那样, .matches()开销.matches()
 /**
 * 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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM