views:

63

answers:

3

i dont know how to generate a regex that can represent empty string in java

+2  A: 

I don't know about Java specifically, but ^$ usually works (^ matches only at the start of the string, $ only at the end).

Chris
+8  A: 

The regex ^$ matches only empty strings (i.e. strings of length 0). Here ^ and $ are the beginning and end of the string anchors, respectively.

If you need to check if a string contains only whitespaces, you can use ^\s*$. Note that \s is the shorthand for the whitespace character class.

Finally, in Java, matches attempts to match against the entire string, so you can omit the anchors should you choose to.

References

API references


Non-regex solution

You can also use String.isEmpty() to check if a string has length 0. If you want to see if a string contains only whitespace characters, then you can trim() it first and then check if it's isEmpty().

polygenelubricants
+1 for mentioning the String.isEmpty() method.
Tim Bender
thanks for the info.The regex solution worked :). I use a validator and that required a regex to be specified.Anyways thanks a lot
prabha
A: 

For checking empty string i guess there is no need of regex itself... u Can check length of the string directly ..

in many cases empty string and null checked together for extra precision.

like String.length >0 && String != null

neo_r23