Regex number range for numbers preceding with zeros
There are a couple ways you can do this. My first thought is something like this:
/^0*(1000|[1-9]\d{0,2})$/
Explanation:
The 0*
consumes any leading zeroes. After that, you're looking for either 1000 or a 1- to 3-digit number that doesn't start with zero. The [1-9]
requires that at least one nonzero digit is present, and the \d{0,2}
allows up to two digits after that (so numbers ending in zero are still allowed).
^(1000|0?[1-9][0-9][0-9]|0{0,2}[1-9][0-9]|0{0,3}[1-9])$
,
or equivalent
^(1000|0?[1-9]\d{2}|0{0,2}[1-9]\d|0{0,3}[1-9])$
will do the trick: all from 0001 to 1000 with or without leading 0's but no more than 4 digits:
- 1st group: only 1000, no leading 0's
- 2nd group: 100-999, up to 1 leading 0
- 3rd group: 10-99, up to 2 leading 0's
- 4th group: 1-9, up to 3 leading 0's
What about this here:
^(1000|(?=\d{1,4})0*[1-9]\d{0,2})$
This is to my opinion the shortest solution, that restricts the maximum allowed digits to 4 and the maximum number to 1000.
I check the start and the end with anchors to prevent that there is something else. Then check for 1000. The second part is then the different one.
(?=\d{1,4})
is a zero length lookahead assertion. That means a non consuming thing that just checks if there are between 1 and 4 numbers. If this is true then continue, else no match. Then just check if there is something with leading 0's and up to 3 numbers at the end.
This can be checked online here: http://regexr.com