Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression for Range (2-16)

Tags:

I want to match a number between 2-16, spanning 1 digit to 2 digits.

Regular-Expressions.info has examples for 1 or 2 digit ranges, but not something that spans both:

The regex [0-9] matches single-digit numbers 0 to 9. [1-9][0-9] matches double-digit numbers 10 to 99.

Something like ^[2-9][1-6]$ matches 21 or even 96! Any help would be appreciated.

like image 546
Jerrold Avatar asked Aug 10 '10 16:08

Jerrold


People also ask

How do you specify a range in regex?

To show a range of characters, use square backets and separate the starting character from the ending character with a hyphen. For example, [0-9] matches any digit. Several ranges can be put inside square brackets.

What does ?= Mean in regex?

?= is a positive lookahead, a type of zero-width assertion. What it's saying is that the captured match must be followed by whatever is within the parentheses but that part isn't captured. Your example means the match needs to be followed by zero or more characters and then a digit (but again that part isn't captured).

How do you write numbers in regex?

Definition and Usage. The [0-9] expression is used to find any character between the brackets. The digits inside the brackets can be any numbers or span of numbers from 0 to 9. Tip: Use the [^0-9] expression to find any character that is NOT a digit.

How do you restrict length in regex?

The ‹ ^ › and ‹ $ › anchors ensure that the regex matches the entire subject string; otherwise, it could match 10 characters within longer text. The ‹ [A-Z] › character class matches any single uppercase character from A to Z, and the interval quantifier ‹ {1,10} › repeats the character class from 1 to 10 times.


2 Answers

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

will match either a single digit between 2 and 9 inclusive, or a 1 followed by a digit between 0 and 6, inclusive.

like image 96
cHao Avatar answered Oct 20 '22 07:10

cHao


With delimiters (out of habit): /^([2-9]|1[0-6])$/

The regex itself is just: ^([2-9]|1[0-6])$

like image 41
eldarerathis Avatar answered Oct 20 '22 09:10

eldarerathis