range of comma separated numbers in regex

Viewed 31

I'm trying to test if a string matches the following string format using regex. It doesn't have to be these exact digits but any digits.

"1000-3000,5000-6000,6000-7000"

Below is what I have tried so far:

/[0-9]+(,[0-9]+)*/g

1 Answers

Your regexp matches a sequence of numbers, not ranges, because it doesn't match - between the numbers. \d+-\d+ matches two numbers separated by -.

And you should anchor it if you want to test that the whole string matches, not a substring.

/^\d+-\d+(,\d+-\d+)*$/
Related