Bronwyn Sheldon
Bronwyn Sheldon

Reputation: 201

String Pattern Matching python

For my program

I have a series of command line arguments that I need to check if they are valid before proceeding with the rest of the program.

One of the argument comes in the format

HH:MM(AM/PM) or HH:MM(am/pm)

examples: 11:20pm is valid or 11:40PM is valid but 11:32 is invalid (It is an expression of a 12Hr digital clock with a AM/PM at the end.

This is the regex expression I have come up with

mo = re.search(r'[0-1][0-2]:[0-5][0-9][APap][Mm]', time)

however what I need to do is come up with a way of checking if the time variable matches the set pattern

Upvotes: 1

Views: 75

Answers (1)

TigerhawkT3
TigerhawkT3

Reputation: 49320

Attempt to match it with datetime.datetime.strptime() and handle the error if it fails (with whatever behavior you'd like).

for s in ('11:20pm', '11:40PM', '11:32'):
    try:
        print(datetime.datetime.strptime(s, '%H:%M%p'))
    except ValueError:
        print('No.')

Result:

1900-01-01 11:20:00
1900-01-01 11:40:00
No.

Upvotes: 7

Related Questions