Regex for checking a comma separated range.

I came up with this regex:

(?:[0-9]{4}-([0-9]{4}|[?]))+ 

for this text:

 1993-2000,2004-? 

Regular expression to capture on the block = [0-9]{4}-([0-9]{4}|[?])

I have options like:

  1993-?
 1993-2000
 1993-2000,2004-?
 1993-2000,2004-2010

etc.

My regular expression captures the blocks [1993-2000] and [2004-?] , But not the comma.

What I find difficult is to declare that a comma must be required for the second, third, etc.

So, what should not be allowed:

  1993-2000,
 1993-20002007-?
 ? -2000

Perhaps this can be resolved to0: 1993-2000,2004,2007,2010-?

Can someone help me get the latest understanding of the conditional comma for second and subsequent events?

I found this regex that I adapted a bit:

 ^([0-9]{4}(-([0-9]{4}|[?]))?)(,([0-9]{4}(-([0-9]{4}|[?]))?))*$ 

This seems to be a trick, but is this the best version?

+4
source share
1 answer

Your regex (last) looks good enough. There should be no problem with excessive rejection or excessive acceptance. However, there are two unnecessary groups:

 ^[0-9]{4}(-([0-9]{4}|[?]))?(,[0-9]{4}(-([0-9]{4}|[?]))?)*$ 

You can make all groups non-exciting because you are checking and not collecting any text:

 ^[0-9]{4}(?:-(?:[0-9]{4}|[?]))?(?:,[0-9]{4}(?:-(?:[0-9]{4}|[?]))?)*$ 

\d can be used instead of [0-9] , but I think that this does not hurt to clearly state this.

+2
source

All Articles