1

I'm trying to come up with a regex to extract time out of a string to build an application.

Here's what I've got so far. Not sure what am I doing wrong here.

https://regex101.com/r/fC0lI5/1

I can get some the string but not all of the different variations.

([01]?[0-9]*:?[0-9]*[AP]M?)-([01]?[0-9]*:?[0-9]*[AP]M?) 8-8:30AM MON TUES THURS FRI 8-10:30AM MON TUES THURS FRI 8:30AM-10:30AM MON TUES THURS FRI 10:30AM-11:30AM MON TUES THURS FRI 10:30AM-11:30AM MON TUES THURS FRI 8AM-8:30AM 10-11PM 

What I want is two captured groups. So I know that the first group is FROM time and the later one is TO time.

3 Answers 3

5
([01]?[0-9]+:?[0-9]*(?:[AP]M)?)-([01]?[0-9]+:?[0-9]*(?:[AP]M)?) ^^ ^^ ^^ ^^ 

Just make AM component optional.See demo.Also make first part + or else it will match empty strings.

https://regex101.com/r/fC0lI5/2

Sign up to request clarification or add additional context in comments.

4 Comments

yours will match 10M-12M, which doesn't make sense
This matches 10:30A-10:31M
[AP]?M? should be instead (?:[AP]M)?
This matches a lot more than needed: 3782328328-23 for example
5

The AM/PM in either capture group is not optional

([01]?[0-9]+:?[0-9]*(?:[AP]M)?)-([01]?[0-9]+:?[0-9]*(?:[AP]M)?) 

I think mine is more valid than the others because the others will allow (they've since fixed theirs)

8M-9M, which is not valid. 

Comments

2

As pointed by other answers, the A and P are not optional. Furthermore, your regex will match other strings (like ":A-:A" or "98387899A-A").

This works and will be stricter that yours:

((?:[01]?[0-9]:)?[0-9]{1,2}(?:AM|PM)?)-((?:[01]?[0-9]:)?[0-9]{1,2}(?:AM|PM)?) 

See the Python manual for a complete description of the regex syntax.

1 Comment

We actually cannot use regex to validate time ...it would be tough....like this will match 0-0.nonetheless plus one

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.