eric eric - 1 year ago 132
Javascript Question

Regex - checking range of numbers with constraints

In javascript I need to parse a user input. The input is of the format:

number - number
. This can be repeated and separated by commas.
The following are some examples:


Here is the regex I wrote for this


However, there are 2 constraints.

  1. The first number must be less than the second number ( 4-5 is valid but 5-4 is not)

  2. Every number must be between 1 and N (inclusive). I will specify N.

Is there a way I can enforce these constraints with regex?

Answer Source

While you can certainly match the format with regexes, you can't do the kind of verification you want with them. What I would recommend is something like this (in JS):

function verifyList(list) {
    var matches = list.match(/\d+-\d+/g);
    for (match in matches) {
        var numbers = match.match(/(\d+)-(\d+)/);
        if (numbers[1] >= numbers[2]) return false;

    return true;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download