2

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').

5 Answers 5

1

try this pattern this is exact requirement as you specified

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

Live Demo: http://regexr.com?34hhp

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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

Comments

0

This regex should work for you:

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

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

Comments

0
function test(r){
    return  "01, 03, 05-08, 10".match(r) && 
            !"01, 03, 05-08,".match(r)
}

test(/^(\d+(-\d+)?,\s*)*\d+$/)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.