Regular expression to check Not Null values and empty strings

54,626

Solution 1

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.

Solution 2

".*\\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.

Share:
54,626
Ratha
Author by

Ratha

Updated on July 05, 2022

Comments

  • Ratha
    Ratha almost 2 years

    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.

  • Tim Pietzcker
    Tim Pietzcker about 10 years
    Anchors are unnecessary with the .matches() method.