-1

I need a Java regular expression, which checks that the given String is not Empty and not null . However the expression should ingnore if the user has accidentally given whitespace in the beginning of the input, but allow whitespaces later on.

4

4 回答 4

8

You could do it without using regex.

boolean check(String s) {
  return s != null && s.trim().length() > 0;
}
于 2012-04-10T13:09:52.303 回答
3

You can use Guava to check for nullity and emptiness:

Strings.isNullOrEmpty(myString);

And you cannot use regular expressions on a null String.

于 2012-04-10T13:10:30.040 回答
2

Try this:

yourString != null && yourString.trim().length() > 0
于 2012-04-10T13:10:38.927 回答
0

您无法在 Java 中使用正则表达式检查空引用。您必须单独检查引用不为空,然后将字符串与正则表达式进行比较。

public static boolean isNullEmptyOrWhitespace(String s) {
  return (s==null) || s.matches("^\\s*$");
}
于 2012-04-10T13:13:55.973 回答