regular expression to allow only numbers in range 1-20

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

this is what I have so far

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

but it doesn't work.

Upvotes: 14

Views: 37539

Answers (3)

ruakh
ruakh

Reputation: 183476

The problem is that | has lower precedence than ^ and $, so your pattern means ^[1-9] or 0[1-9] or 1[0-9] or 2[0]$: only single-digit values are restricted by ^, and only 20 is restricted by $.

You can either repeat ^ and $ in each branch of the alternation, or else wrap the alternation in (?:...) to create a non-capturing subexpression:

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

(I've also taken the liberty of changing [0] to 0.)

Upvotes: 17

tristram shandy
tristram shandy

Reputation: 181

How 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'm assuming perl-style regular expressions, since you didn't specify the context.

Upvotes: 9

try this

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

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

Upvotes: 4

Related Questions