Ratha
Ratha

Reputation: 9692

Regular expression to check Not Null values and empty strings

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.

Upvotes: 5

Views: 75388

Answers (3)

spikeheap
spikeheap

Reputation: 3887

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

Upvotes: 0

La-comadreja
La-comadreja

Reputation: 5755

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

Upvotes: 5

Sabuj Hassan
Sabuj Hassan

Reputation: 39375

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.

Upvotes: 6

Related Questions