Regular Expression: Numeric range

I don't think regex is the right choice for this. Have you tried parsing the value? If you have to use regex I would match \d{1,3} parse the string and then validate the number in code.


The easiest way for this would be to parse the string as a number and look for the number to be in the proper range.

To do this with pure regex you need to identify the pattern and write it out:

^(0?[0-9]{1,2}|1[0-7][0-9]|180)$

This has three alternatives: one for single- and two-digit numbers (allowing leading zeroes), where each digit can be anything from 0 to 9. And another one that specifies what range of digits is allowed for each digit in a three-digit number. In this case, this means that the first digit needs to be 1, the second between 0 and 7 and the last one may be anything. The third alternative is just for the number 180 which didn't fit nicely into the pattern elsewhere.

A more straightforward approach might be

^(0{0,2}[0-9]|0?[1-9][0-9]|1[0-7][0-9]|180)$

which just alternates for each tricky numeric range there might be.

Tags:

Regex