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:
... 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.
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:
Edit: Added for wildcard *
as per OP's comment.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With