Reputation: 16856
I am trying to write an RegExp that matches something like 01, 03, 05-08, 10
but does not match 01, 03, 05-08,
(because the squence has to end with a number).
So basically my "string" consists of /(\-?\d+)\-(\-?\d+)/
(e.g. 01-05 or -5-10) every instance of this pattern is seperated by a comma.
I tried a looong time with RegExr but couldn't find a solution for my problem. Here is my try: http://regexr.com?34hh1
With the RegExp I want to do SEQUENCE_EXP.test('some string').
Upvotes: 2
Views: 3268
Reputation: 474
function test(r){
return "01, 03, 05-08, 10".match(r) &&
!"01, 03, 05-08,".match(r)
}
test(/^(\d+(-\d+)?,\s*)*\d+$/)
Upvotes: 0
Reputation: 2176
try this pattern this is exact requirement as you specified
^(-?\d+(--?\d+)?,\s?)*-?\d+(--?\d+)?$
Live Demo: http://regexr.com?34hhp
Upvotes: 1
Reputation: 785058
This regex should work for you:
^(?:\d+(?:-\d+)?,)*\d+$
Upvotes: 0
Reputation: 1906
So, you have two patterns, a valid number \d+
And \d+-\d+
So the NUMBER_PATTERN
must be \d+(-\d+)?
And a sequence NUMBER_PATTERN[, NUMBER_PATTERN]*
What about this:
/\d+(-\d+)?(, \d+(-\d+)?)*$/
Take a look http://regexr.com?34hhj
Upvotes: 0
Reputation: 8053
You can use the $
operator to indicate the string has to end with the expression. In your case you could try:
/^((-?\d+(-\d+)?)\s*,\s*)+(-?\d+(-\d+)?)$/
Note that you don't have to escape the -
outside of square brackets.
Upvotes: 0