Home > database >  How to check dash after repeating groups in regex
How to check dash after repeating groups in regex

Time:11-12

Sample string:

MON,00:00-10:00-11:00-13:00-15:00-16:00;TUE,00:00-23:59;

Regex:

^((MON|TUE|WED|THU|FRI|SAT|SUN),(([01][0-9]|2[0-3]):([0-5][0-9])-([01][0-9]|2[0-3]):([0-5][0-9])) ;) $

Here I want to check dash is there (not optional) after every interval of start and end time.

00:00-10:00
11:00-13:00
15:00-16:00

So the above will be

00:00-10:00-11:00-13:00-15:00-16:00

CodePudding user response:

You have a day, then pairs of time parts with a - and optionally repeated with also a - in between ending on a ;

To match that format over the whole line, you can repeat those parts over the whole line.

^(?:(?:MON|TUE|WED|THU|FRI|SAT|SUN),(?:[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])*;) $

Regex demo

Using a capture group to match the pairs of intervals for a single part:

^(?:MON|TUE|WED|THU|FRI|SAT|SUN),((?:[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])*);

Regex demo

  • Related