regex for number between numbers

DaCh picture DaCh · Jun 8, 2016 · Viewed 15.4k times · Source

I'm in need of a regex, which takes a minimum and a maximum number to determine valid input, And I want the maximum and minimum to be dynamic.

I have been trying to get this done using this link https://stackoverflow.com/a/13473595/1866676

But couldn't get it to work. so can someone please let me know how to do this.

------ Update on Wiktor Stribiżew request---------

Let say i want to make a html5 input box, And i Want it to only receive numbers from 100 to 1999

What would i regex like this look like? the regex expression itself, should have anything to do with what code there should use it, as i'M going to use this on android, iOS and web pages

Answer

yosefrow picture yosefrow · Jun 8, 2016

Here's how that kind of regex works

ones: ^[0-9]$  // just set the numbers -- matches 0 to 9
tens: ^[1-3]?[0-9]$ //set max tens and max ones -- matches 0 to 39
tens where max does not end in 9 ^[1-2]?[0-9]$|^[3][0-4]$ // 0 to 34
only tens: ^[1][5-9]$|^[2-3][0-9]$|^[4][0-5]$ // 15 to 45

Here, lets pick an arbitrary number 1234 to 2345

^[1][2][3][4-9]$|
^[1][2][4-9][0-9]$|
^[1][3-9][0-9][0-9]$|
^[2][0-2][0-9][0-9]$|
^[2][3][0-3][0-9]$|
^[2][3][4][0-5]$

https://regex101.com/r/pP8rQ7/4

Basically the ending of the middle series always needs to be a straight range that can reach 9 unless we are dealing with the ones place, and if it cant, you have to build it upwards toward the middle each time we have a value that can't start in 0 and then once we reach a value that cant end in 9 break early and set it in the next condition.

Notice the pattern, as each place solidifies. Also keep in mind that when dealing with going from lower to higher places, optional operators ? should be used.

Its a bit complex, but its nowhere near impossible to design a custom range with a bit of thought.

If you are more specific, we can craft an exact example, but this is generally how it is done:beginning-range|middle-range|end-range You should only need beginning or end-ranges in certain cases like if the min or max does not end in 9. the ? means that the range that comes after it is optional. (so for example in the first case it lets us have both single and double numbers.

so for 100 - 1999 it's quite simple actually because you have lots of 9's and 0's

/^[1-9][0-9][0-9]$|^[1][0-9][0-9][0-9]$/

https://regex101.com/r/pP8rQ7/1

Note: Single values don't need ranges [n] I just added them for readability.

Update: Almost 3 years later, discovered there is a range generator. I don't know how reliable it is, but it looks good at first glace: http://gamon.webfactional.com/regexnumericrangegenerator/