Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to allow range of numbers, or null

Tags:

java

regex

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

like image 654
Jimmy Avatar asked Aug 06 '10 09:08

Jimmy


People also ask

How do you specify a number range in regex?

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)".

Can a regular expression be empty?

∅, the empty set, is a regular expression. ∅ represent the language with no elements {}.

How do I check if a number is only in regular expressions?

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.

Can you use or in regex?

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.


1 Answers

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.

like image 63
aioobe Avatar answered Nov 09 '22 10:11

aioobe