Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match either range or list of numbers

Tags:

regex

I need a regex to match lists of numbers and another one to match ranges of numbers (expressions shall never fail in both cases). Ranges shall consist of a number, a dash, and another number (N-N), while lists shall consist of numbers separated by a comma (N,N,N). Here below are some examples.

Ranges:

'1-10' => OK
Whateverelse => NOK (e.g. '1-10 11-20')

List:

'1,2,3' => OK
Whateverelse => NOK

And here are my two regular expressions:

  1. [0-9]+[\-][0-9]+
  2. ([0-9]+,?)+

... but I have a few problems with them... for example:

When evaluating '1-10', regex 2 matches 1... but it shouldn't match anything because the string does not contain a list.

Then, when evaluating '1-10 11-14', regex 1 matches 1-10... but it shouldn't match anything because the string contains more than just a range.

What am I missing? Thanks.

like image 437
j3d Avatar asked Jul 19 '13 11:07

j3d


1 Answers

Try this:

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

Test results:

1-10         OK
1,2,3        OK
1-*          OK
*-10         OK
1,2,3 1-10   NOK
1,2,3 2,3,4  NOK
*-*          NOK

Visualization of the regex:

Visualization of the regex

Edit: Added for wildcard * as per OP's comment.

like image 172
unlimit Avatar answered Sep 18 '22 10:09

unlimit