Arnab Shaw
Arnab Shaw

Reputation: 539

Regex for particular given range "001 to 150"

Here is what I have tried but unable get a desired result. Case1:

^(00[1-9]|0[1-9][0-9]|1[0-5][0-9])$

it is accepting ranges from 001-159 as I have give [0-9]

For Case2:

^(00[1-9]|0[1-9][0-9]|1[0-50][0])$

it is accepting 110, 120... and 150 as last accepted digit is "0".

The Desired Result should only accept 001-150 Your help will be much appreciated.

Upvotes: 0

Views: 1774

Answers (2)

Patrick Artner
Patrick Artner

Reputation: 51653

You can use:

^(00[1-9])|(0[1-9]\d)|(1[0-4]\d)|(150)$

which will match:

  • 00 followed by 1-9
  • 0 followed by 1-9 followed by any digit
  • 1 followed by 0-4 and any digit
  • or 150

The groups are mutually exclusive, so only one should ever match, if any.

Upvotes: 0

Sebastian Proske
Sebastian Proske

Reputation: 8413

If at all possible, try to parse those as integers and do the range check in the programming language of your choice.

Other than that, your first approach was close, just restrict the 3rd alternation to 149 and add 150 as separate value, like

^(00[1-9]|0[1-9][0-9]|1[0-4][0-9]|150)$

Upvotes: 5

Related Questions