Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regular expression to allow only numbers in range 1-20

Tags:

regex

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.

like image 652
Gold Skull with Pattern Avatar asked Aug 29 '12 17:08

Gold Skull with Pattern


People also ask

How do you specify a number range in regex?

With regex you have a couple of options to match a digit. You can use a number from 0 to 9 to match a single choice. Or you can match a range of digits with a character group e.g. [4-9]. If the character group allows any digit (i.e. [0-9]), it can be replaced with a shorthand (\d).

What is the regular expression for numbers only?

To check for all numbers in a field To get a string contains only numbers (0-9) we use a regular expression (/^[0-9]+$/) which allows only numbers. Next, the match() method of the string object is used to match the said regular expression against the input value.

How do you restrict in regex?

Go to the question's Settings. Go to Validation Criteria and choose the Manually enter your validation logic in XLSForm code option. In the Validation Code box, enter your regex formula between the quotation marks (' ') of the regex(., ' ') format.

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.


2 Answers

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

like image 92
ruakh Avatar answered Sep 20 '22 21:09

ruakh


try this

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

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

like image 23
Victor 'Chris' Cabral Avatar answered Sep 21 '22 21:09

Victor 'Chris' Cabral