I'm trying to write a JavaScript regular expression to only allow the following inputs:
So far, I have the following expression:
^[0-9]$|^[0-9]+$|^[0-9](-?,?[0-9])*$
However, this is allowing 1-1-1
, which I do not want. A hyphen can only appear if not followed by another number-hyphen-number combo.
This link might help: http://regexr.com?34ljt
The following samples should evaluate as being valid:
01,03,05-08,10
01,03,05
01,03,05-08
01
1,1,5-6,1,1
1,1,5-6,1,1-3
12,12,1-9
1-9,5,5
1-9,9,9,5-6
1-2
11-11
11,11
1,1
1,1,1
11,11,11
1111
1,1,1,1,1,1
1
56,1
1,1
1,3
1,3,4,5
1,3
The following samples should evaluate as being invalid:
sdfdf
11-11-11-11
1-1-1-1-1
f
01,
01,03,05-08,
-1,4-,-5,8909
1,1,1-1-1
1,1,11-1111-1
1-1-1
1,,1
1--1
1-
1,,
,-1-
df
-1
,1
Try
/^\d+(-\d+)?(,\d+(-\d+)?)*$/
Further to the comments
One way to prevent a match if there are consecutive ranges is to add a negative look-ahead
(?!.*-\d+,\d+-)
so the regex becomes
/^(?!.*-\d+,\d+-)\d+(-\d+)?(,\d+(-\d+)?)*$/
If the pattern inside the negative look-ahead can be matched it prevents the whole regular expression from matching. The .*
is used so that if e.g. -1,1-
is found anywhere ahead in the string, a match will be prevented.