-2

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.

7
  • 1
    "ignore" whitespace at the beginning: does that mean " " and " test" fail or pass validation? Commented Apr 10, 2012 at 13:10
  • 2
    You cannot check for a null reference with a regular expression in Java. You must separately check that the reference is not null then compare the string with a regular expression. Commented Apr 10, 2012 at 13:11
  • @maerics thank you but the thing is that my boss told me to dat using regex only how can i explain him Commented Apr 10, 2012 at 13:12
  • 2
    your boss told you to do this? I recommend going to careers.stackoverflow.com and submitting a resume. Commented Apr 10, 2012 at 13:14
  • 1
    To perform a regalur expression check you need to have a String to check. null is not a String object. Commented Apr 10, 2012 at 13:14

4 Answers 4

8

You could do it without using regex.

boolean check(String s) {
  return s != null && s.trim().length() > 0;
}
Sign up to request clarification or add additional context in comments.

2 Comments

@user1324126 that is a terrible idea.
@Woot4Moo its not a good idea but still necessary for certain things
3

You can use Guava to check for nullity and emptiness:

Strings.isNullOrEmpty(myString);

And you cannot use regular expressions on a null String.

Comments

2

Try this:

yourString != null && yourString.trim().length() > 0

Comments

0

You cannot check for a null reference with a regular expression in Java. You must separately check that the reference is not null then compare the string with a regular expression.

public static boolean isNullEmptyOrWhitespace(String s) {
  return (s==null) || s.matches("^\\s*$");
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.