A regular expression for a range of numbers or a null value

I have the following regex, how to change it to also allow null?

[0-9]{5}|[0-9]{10}

I would like this to allow a 5 digit number, 10 digit number or null

thanks

+4
source share
3 answers

If by null you mean an empty string, you want:

 ^(?:[0-9]{5}|[0-9]{10}|)$ 
+5
source

Just add |null :

 [0-9]{5}|[0-9]{10}|null 

As you probably know | is the "or" operator, and the null character string matches the word null. Thus, it can be considered as <your previous pattern> or null .


If you want the pattern to match the null string, the answer is that this is not possible. That is, you cannot do, for example, Matcher.matches() return true for a null input string. If this is what you need, you can get away with using the above expression and not match with str , but with ""+str , which will result in "null" if str actually null .

+11
source
 [0-9]{5}|[0-9]{10}|null 

must do it. Depending on how you use the regular expression, you may need to bind it to make sure that it will always match the entire string, not just the five-digit substring inside the eight-digit string:

 ^(?:[0-9]{5}|[0-9]{10}|null)$ 

^ and $ bind regex, (?:...) is not an exciting group containing alternation.

Edit: If you mean null == "empty string", use

 ^(?:[0-9]{5}|[0-9]{10}|)$ 
+4
source

All Articles