I am working on a regular expression for time pattern in Python: hours [1-12] followed by :, then minutes [00:59] followed by an optional space and am or PM in upper- or lowercase.
Here is the code:
def check_time(text):
pattern = r"^(1[0-2]|0?[1-9]):([0-5]?[0-9])(\s?[AP]M)?$ "
result = re.search(pattern, text)
return result != None
print(check_time("12:45pm")) # Expected True
print(check_time("9:59 AM")) # Expected True
print(check_time("6:60am")) # Expected False
print(check_time("five o'clock")) # Expected False