Regex number range for numbers preceding with zeros
How do I form a regex to validate a range from 1 to 1000, where the number 001 is same as 1, 0245 is same as 245. Most solutions I saw allowed the range check but did not allow the number to start with 0. The problem is with not allowing 0,00,000, but allow the number to start with or without 0.
Edit: it should allow 1,01,001 and not any numbe开发者_开发知识库r exceeding 4 digits.
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
myregexp.com
regexp: ^(0+)?(?=\d{1,4})([1-9]|[1-9][0-9]|[1-9][0-9][0-9]|1000)$
0001000 matches 0001001 doesn't match 0..1000 matches anything above 1000 doesn't match
/^((1000)|(0\d{1,3})|(\d{1,3}))$/
Matches
1000
100
0001
01
1
010
0010
0100
Does not match
10000
00001
Proof available at http://refiddle.com/10l
精彩评论