toy
toy

Reputation: 12141

What's wrong with my regex to extract time from a string?

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.

Upvotes: 1

Views: 418

Answers (3)

Patrick Fournier
Patrick Fournier

Reputation: 668

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.

Upvotes: 2

Tyler Sebastian
Tyler Sebastian

Reputation: 9458

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.

Upvotes: 5

vks
vks

Reputation: 67968

([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

Upvotes: 5

Related Questions