5

What would be the regular expression to check a string value is "Not null and not empty" in java? i tried like this "/^$|\s+/", but seems not working.

4
  • 2
    Is this the question, really? Commented Feb 28, 2014 at 16:38
  • So you consider " " to be "empty"? Commented Feb 28, 2014 at 16:41
  • 1
    The regex /^$|\s+/ equates to 'empty string OR any string containing at least one whitespace character' Commented Feb 28, 2014 at 16:43
  • 1
    Also, why the slashes? Java isn't PHP, it doesn't have regex delimiters (but it does require backslashes to be escaped)... Commented Feb 28, 2014 at 16:43

3 Answers 3

6

Considering this: your string can not contain "null" as string:

String.valueOf(input).matches("^null|$");

Otherwise check input != null and remove null| from the regex.

Sign up to request clarification or add additional context in comments.

1 Comment

Anchors are unnecessary with the .matches() method.
5
".*\\S+.*"

This means there is at least one non-whitespace character in the string. But you should watch out—if you call the string as an implicit parameter and it's null, you'll see a NullPointerException. Thus, it's probably better to check for null using conditionals.

Comments

0

You cannot check for not-null using a regular expression, because that regex is run against the String.

To check the String isn't empty you can just use !myString.isEmpty()

so if(myString != null && !myString.isEmpty())

Of course, in Groovy it would just be if(myString) ;)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.