Reputation: 16428
I have the following Regular Expression, how can I modify it to also allow null?
[0-9]{5}|[0-9]{10}
I would like it to allow a 5 digit number, a 10 digit number, or null
Thanks
Upvotes: 10
Views: 74866
Reputation: 336498
[0-9]{5}|[0-9]{10}|null
should do it. Depending on how you are using the regex, you might need to anchor it in order to be sure that it will always match the entire string and not just a five-digit substring inside an eight-digit string:
^(?:[0-9]{5}|[0-9]{10}|null)$
^
and $
anchor the regex, (?:...)
is a non-capturing group that contains the alternation.
Edit: If you mean null
=="empty string", then use
^(?:[0-9]{5}|[0-9]{10}|)$
Upvotes: 5
Reputation: 30081
If by null you mean the empty string, you want:
^(?:[0-9]{5}|[0-9]{10}|)$
Upvotes: 7
Reputation: 421340
Just append |null
:
[0-9]{5}|[0-9]{10}|null
As you probably know, |
is the "or" operator, and the string of characters null
match the word null. Thus it can be read out as <your previous pattern> or null
.
If you want the pattern to match the null-string, the answer is that it's impossible. That is, there is no way you can make, for instance, Matcher.matches()
return true for a null input string. If that's what you're after, you could get away with using the above regexp and matching not on str
but on ""+str
which would result in "null"
if str
actually equals null
.
Upvotes: 17