Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex number range for numbers preceding with zeros

Tags:

regex

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 number exceeding 4 digits.

like image 945
Rnet Avatar asked Apr 14 '11 04:04

Rnet


1 Answers

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

like image 70
Justin Morgan Avatar answered Sep 25 '22 21:09

Justin Morgan