Jerrold
Jerrold

Reputation: 1564

Regular Expression for Range (2-16)

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.

Upvotes: 25

Views: 67684

Answers (6)

Dheeraj Bhavsar
Dheeraj Bhavsar

Reputation: 57

Just replace your input formatters with

inputFormatters: [
                    FilteringTextInputFormatter(
                      RegExp(
                          r'^([0-9]|[2-8][0-9]|1[0-9]|9[0-9]|[2-8][0-9][0-9]|1[1-9][0-9]|10[0-9]|9[0-8][0-9]|99[0-9]|[2-4][0-9][0-9][0-9]|1[1-9][0-9][0-9]|10[1-9][0-9]|100[0-9]|500[0-0])$'),
                      allow: true,
                    )
                  ],

Upvotes: 1

ASHWIN RAJEEV
ASHWIN RAJEEV

Reputation: 2891

Use the python package regex_engine for generating regular expressions for numerical ranges

You can install this package with pip.

pip install regex-engine
from regex_engine import generator

generate = generator()
    
regex = generate.numerical_range(2, 16)
    
print(regex)
^([2-9]|1[0-6])$

You can also generate regexes for floating point and negative ranges.

from regex_engine import generator

generate = generator()

regex1 = generate.numerical_range(5, 89)
regex2 = generate.numerical_range(81.78, 250.23)
regex3 = generate.numerical_range(-65, 12)

Upvotes: 4

user3662963
user3662963

Reputation: 1

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

By specifying start and stop for each set of numbers you are looking for your regex won't also return 36, 46, ... and so on. I tried the above solution and found that this works best for staying within the range of 2-16.

Upvotes: -2

alecov
alecov

Reputation: 5171

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

(Edit: Removed quotes for clarification.)

Upvotes: 2

eldarerathis
eldarerathis

Reputation: 36213

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

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

Upvotes: 10

cHao
cHao

Reputation: 86535

^([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.

Upvotes: 50

Related Questions