Fred
Fred

Reputation: 414

regex for repeating values

I am trying to find the correct regex (for use with Java and JavaScript) to validate an array of day-of-week and 24-hour time formats. I figured out the time format but am struggling to come up with the full solution.

The regex needs to validate patterns which include one or more of the following, separated by a comma.

{two-character day} HH:MM-HH:MM

Three examples of valid strings would be:

M 5:30-7:00
M 5:30-7:00, T 5:30-7:00, W 18:00-19:30
F 12:00-14:30, Sa 6:45-8:15, Su 6:45-8:15

Upvotes: 0

Views: 972

Answers (6)

methai
methai

Reputation: 9143

This will capture all sets in an array. The T in the short day of week list is debatable (tuesday or thursday?).

^((?:[MTWFS]|Tu|Th|Sa|Su)\s(?:[0-9]{1,2}:[0-9]{2})-(?:[0-9]{1,2}:[0-9]{2})(?:,\s)?)+$

The (?:) are non-capturing groups, so your actual matches will be (for example):

  • M 5:30-7:00
  • T 5:30-7:00
  • W 18:00-19:30

But the entire line will validate.

Added ^ and $ for line boundaries and an explicit time-time match because some regular expression parsers may not work with the previous way that I had it.

Upvotes: 0

Mike Brant
Mike Brant

Reputation: 71384

This should do the trick:

^(M|Tu|W|Th|F|Sa|Su) \d{1,2}:\d{2}-\d{1,2}:\d{2}(, (M|Tu|W|Th|F|Sa|Su) \d{1,2}:\d{2}-\d{1,2}:\d{2})*$

Note that you show T in your example above which is ambiguous. You might want to enforce Tu and Th as shown in my regex.

Upvotes: 0

m4573r
m4573r

Reputation: 990

I'd go with this:

(((M|T(u|h)|W|F|S(a|u)) ((1*\d)|(2[0-3])):[1-5]\d-((1*\d)|(2[0-3])):[1-5]\d(, )?)+

Upvotes: 0

errieman
errieman

Reputation: 1949

You could try this: ([MTWFS][ouehra]?) ([0-9]|[1-2][0-9]):([0-6][0-9])-([0-9]|[1-2][0-9]):([0-6][0-9])

Upvotes: 0

ramblex
ramblex

Reputation: 3057

This should validate a 24-hour time:

/^((M|T|W|Th|Fr|Sa|Su) ([01]?[0-9]|2[0-3]):[0-5][0-9]-([01]?[0-9]|2[0-3]):[0-5][0-9](, )?)+$/

Credit for the time bit goes to mkyong: http://www.mkyong.com/regular-expressions/how-to-validate-time-in-24-hours-format-with-regular-expression/

Upvotes: 1

MIE
MIE

Reputation: 454

you can try this

[A-Za-z]{1,2}[ ]\d+:\d+-\d+:\d+

Upvotes: 0

Related Questions