Domanda

Quindi non vedo attraverso alcuni codice legacy e trovando esempio dove fanno questo:

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

Ignorare per il momento che la chiamata .matches(..) crea un nuovo Pattern e Matcher ogni volta (UHG) - ma non v'è alcun motivo per non modificare questa linea:

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

Sono abbastanza sicuro che la regex semplicemente se la stringa è tutti gli spazi. Saranno StringUtils cogliere tutte le stesse condizioni del primo?

È stato utile?

Soluzione

Sì, StringUtils.isBlank(..) farà la stessa cosa, ed è un modo migliore per andare. Date un'occhiata al codice:

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;
}

Altri suggerimenti

Lei ha ragione il test delle espressioni regolari è se la stringa è più zero o più caratteri di spazio bianco.

I vantaggi di non usare l'espressione regolare

  • Le espressioni regolari sono criptici a molte persone, che lo rende meno leggibile
  • E come ha giustamente fatto notare .matches() ha un overhead non banale
 /**
 * 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());
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top