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
Example: Regex Number Range 1-20 Range 1-20 has both single digit numbers (1-9) and two digit numbers (10-20). For double digit numbers we have to split the group in two 10-19 (or in regex: "1[0-9]") and 20. Then we can join all these with an alternation operator to get "([1-9]|1[0-9]|20)".
∅, the empty set, is a regular expression. ∅ represent the language with no elements {}.
To check for all numbers in a field To get a string contains only numbers (0-9) we use a regular expression (/^[0-9]+$/) which allows only numbers.
Alternation is the term in regular expression that is actually a simple “OR”. In a regular expression it is denoted with a vertical line character | . For instance, we need to find programming languages: HTML, PHP, Java or JavaScript.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With