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 に答える