Regular expression for numbers without leading zeros

Updated:

^([0-9]|[1-9][0-9])$

Matches 0-99. Doesn't match values with leading zeros. Depending on your application you may need to escape the parentheses and the or symbol.


There are plenty of ways to do it but here is an alternative to allow any number length without leading zeros

0-99:

^(0|[1-9][0-9]{0,1})$

0-999 (just increase {0,2}):

^(0|[1-9][0-9]{0,2})$

1-99:

^([1-9][0-9]{0,1})$

1-100:

^([1-9][0-9]{0,1}|100)$

Any number in the world

^(0|[1-9][0-9]*)$

12 to 999

^(1[2-9]|[2-9][0-9]{1}|[1-9][0-9]{2})$

^(0|[1-9][0-9]?)$

Test here http://regexr.com?2uu31 (various samples included)

You have to add a 0|, but be aware that the "or" (|) in Regexes has the lowest precedence. ^0|[1-9][0-9]?$ in reality means (^0)|([1-9][0-9]?$) (we will ignore that now there are two capturing groups). So it means "the string begins with 0" OR "the string ends with [1-9][0-9]?". An alternative to using brackets is to repeat the ^$, like ^0$|^[1-9][0-9]?$.

Tags:

Regex