Spark323
Spark323

Reputation: 1585

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:

1-10
4-10,13-17
6-10,3-8,4-12

Here is the regex I wrote for this

(\d+[-]\d+[,]?)

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?

Upvotes: 0

Views: 178

Answers (1)

Sebastian Lenartowicz
Sebastian Lenartowicz

Reputation: 4854

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;
}

Upvotes: 2

Related Questions