I have a regex to validate a string containing ‘HHMM’ or ‘HHMM,HHMM’
This is what I am using:
^[0-2][0-9][0-5][0-9],[0-2][0-9][0-5][0-9]$
This sort of works in that 1247 is ok 3247 is not.
Similarly 1247,2200 is ok but 1247,2290 is not.
However, to allow for 24 hour clock values such as 2500 cannot be allowed.
Is there a way to put a check in regex that if first part of hour is 2 that second part can only be 0-4?
Yes, use
|to separate the0xand1xcases from2y:The
(?:...)creates a non-capturing group, limiting the scope of the|operator. If you did want to capture theHHvalue (e.g. to use it in a replacement later or something), use(...)instead.Update: Allowing
2400but avoiding all other invalid times like2411can be done with another|:However I would argue that it’s better to just disallow any
24MM(including2400) at all since it really should be written00MM. In this case the regex just becomes: