Jonas
Jonas

Reputation: 381

Regex for one element or semi-colon separated list of max. 2 elements

I need to match one or two time-ranges (in 24h-format) in a regex. The following two would be valid entries:

12:30-15:00

12:30-15:00;17:20-20:00

If there is an error anywhere (ie in the second time-range), then no match should be found. ie 12:30-15:00;17:20 is not a valid entry.

The regex for one time range I have written as follows (which could be improved to use only valid times, but that's the next step):

(\d\d:\d\d\-\d\d:\d\d)

Any hints on how to expand this to fit my aforementioned criteria?

Upvotes: 1

Views: 30

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627380

You can use

^(?:[01]?[0-9]|2[0-3]):[0-5][0-9]-(?:[01]?[0-9]|2[0-3]):[0-5][0-9](?:;(?:[01]?[0-9]|2[0-3]):[0-5][0-9]-(?:[01]?[0-9]|2[0-3]):[0-5][0-9])*$

See this regex demo. A shorter PCRE/Onigmo (Ruby) version:

^((?:[01]?[0-9]|2[0-3]):[0-5][0-9]-(?:[01]?[0-9]|2[0-3]):[0-5][0-9])(?:;(\g<1>))*$

See this regex demo.

Details:

  • ^ - start of string (in Ruby, \A)
  • ((?:[01]?[0-9]|2[0-3]):[0-5][0-9]-(?:[01]?[0-9]|2[0-3]):[0-5][0-9]) - Group 1:
    • (?:[01]?[0-9]|2[0-3]):[0-5][0-9] - first time string: an optional 0 or 1 and then any digit, or 2 and then 0, 1, 2 or 3 and then a : char and then a number from 00 to 59
    • - - a hyphen
    • (?:[01]?[0-9]|2[0-3]):[0-5][0-9] - second time string
  • (?:;(\g<1>))* - zero or more occurrences of
    • ; - a semi-colon
    • (\g<1>) - Repeat Group 1 pattern
  • $ - end of string.

Upvotes: 1

Related Questions