Stringutils.isblank vs. Regexp
-
11-10-2019 - |
题
因此,我正在查看一些遗留代码,并找到他们在哪里做的实例:
if ((name == null) || (name.matches("\\s*")))
.. do something
暂时忽略了 .matches(..)
呼叫每次都会创建一个新的模式和匹配器(UHG) - 但是是否有任何理由不将此行更改为:
if (StringUtils.isBlank(name))
..do something
我敢肯定,如果字符串都是所有空格,那么正则是匹配的。 Stringutils会捕获与第一个条件相同的条件吗?
解决方案
是的, 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;
}
其他提示
如果字符串更为零或更多的白空间字符,则正确的正则表达式测试是正确的。
不使用正则表达式的优点
- 正则表达式对许多人来说是神秘的,这使得它不那么可读性
- 正如你正确指出的那样
.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());
}
不隶属于 StackOverflow