Abhishek Ranjan
Abhishek Ranjan

Reputation: 931

Matching a number-range expression with regex

I am trying to match an input of the following format

[Number]-[Number] using regex in JavaScript.

For ex :

  1. 1-100 OK
  2. 200-300 OK
  3. -0992 NOT OK
  4. aa-76 NOT OK
  5. 1- NOT OK

I tried:

^\d+(-\d+)*$

But this does not work at all.

Any pointers?

Upvotes: 0

Views: 370

Answers (2)

zx81
zx81

Reputation: 41838

The reason it doesn't work is that the * quantifier makes the (-\d+) optional, allowing the regex to simply match 222. Remove it and all will be well. If you don't need the parentheses, strip them:

^\d+-\d+$

What if you want your numbers to be between 0 and 100 as in title?

If you want to make sure that your numbers on each side are in the range from 1 to 100, without trailing zeros, you can use this instead of \d:

100|[1-9]\d|\d

Your regex would then become:

^(?:100|[1-9]\d|\d)-(?:100|[1-9]\d|\d)$

What if the left number must be lower than the right number?

The regexes above will accept 2222-1111 for the first, 99-12 for the second (for instance). If you want the right number to be greater than the lower one, you can capture each number with capturing parentheses:

^(\d+)-(\d+)$

or

^(100|[1-9]\d|\d)-(100|[1-9]\d|\d)$

Then, if there is a match, say

if(regexMatcher.group(2) > regexMatcher.group(1)) { ... success ...}

Upvotes: 4

Stefano Sanfilippo
Stefano Sanfilippo

Reputation: 33046

The regex you are looking for is /\d+-\d+/. If you don't require the whole line to match the regex, then there is no need for surrounding ^ and $. For instance:

/\d+-\d+/.test("a-100")
// Result: false
/\d+-\d+/.test("-100")
// Result: false
/\d+-\d+/.test("10-100")
// Result: true

Upvotes: 2

Related Questions