A regular expression that allows you to use only numbers in the range 1-20

I want the user to enter numbers in the range 0-20, and they can both enter 01 and 1

that's what i still have

/^[1-9]|0[1-9]|1[0-9]|2[0]$/ 

but that will not work.

+8
regex
source share
3 answers

The problem is that | has lower priority than ^ and $ , so your pattern means ^[1-9] or 0[1-9] or 1[0-9] or 2[0]$ : only single digits are limited ^ , and only 20 limited to $ .

You can either repeat ^ and $ in each branch of the strip, or wrap the strip in (?:...) to create an unrecoverable subexpression:

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

(I also allowed changing [0] to 0 )

+8
source share

What about

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

The problem is that 20 is a special case. The second section covers it. The first section covers the rest. I accept perl-style regular expressions since you did not specify a context.

+6
source share

try it

 /^([01]?\d|20)$/ 

0 or 1 (optional) followed by at least one digit OR 20

+3
source share

All Articles