Sebastian Sebald
Sebastian Sebald

Reputation: 16856

RegExp: Match repeating sequence pattern of numbers

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

Answers (5)

user2264587
user2264587

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

Civa
Civa

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

anubhava
anubhava

Reputation: 785058

This regex should work for you:

^(?:\d+(?:-\d+)?,)*\d+$

Live Demo: http://www.rubular.com/r/QTnbqncycZ

Upvotes: 0

A. Matías Quezada
A. Matías Quezada

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

Kninnug
Kninnug

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

Related Questions