'Regular expression for 12 hours time format

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


Solution 1:[1]

import re
def check_time(text):
  pattern = r"^(?:1[0-2]|[1-9]):(?:[0-5][0-9])(?:\s?[APap][Mm])?$"
  result = re.search(pattern, text)
  return result != None

print(check_time("12:45pm")) # True
print(check_time("9:59 AM")) # True
print(check_time("6:60am")) # False
print(check_time("five o'clock")) # False

Solution 2:[2]

import re
def check_time(text):
  pattern = r'^1[0-2]|[1-9]:[0-5][0-9](\s?[APap][Mm])$'
  result = re.search(pattern, text)
  return result != None

print(check_time("12:45pm")) # True
print(check_time("9:59 AM")) # True
print(check_time("6:60am")) # False
print(check_time("five o'clock")) # False

Solution 3:[3]

import re
def check_time(text):
    pattern = r'[1-9][0-2]?:[0-5][0-9] ?[apAP][mM]'
    result = re.search(pattern, text)
    return result != None

print(check_time("12:45pm")) # True
print(check_time("9:59 AM")) # True
print(check_time("6:60am")) # False
print(check_time("five o'clock")) # False

Solution 4:[4]

import re
def check_time(text):
  pattern = r'([1-9]|1[012]):([0-5][0-9])\s?(am|pm)'
  result = re.search(pattern, text, flags=re.I)
  return result != None

print(check_time("12:45pm")) # True
print(check_time("9:59 AM")) # True
print(check_time("6:60am")) # False
print(check_time("five o'clock")) # False

Explanation
([1-9]|1[012]) => [1-9] match's single digits which start from 1 not from 0 this or condition 1[012] match's two digits ranges 10-12 eg: 1:23 or 10:30

:([0-5][0-9]) => : you know, match's the range 00 - 59 rules out 60 \s?(am|pm) => since space is optional so \s? (am|pm) capture day or evening eg. am or pm result = re.search(pattern, text, flags=re.I) => note flags.I is used as case insensitive

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 AKinsoji Hammed Adisa
Solution 2 Krenil
Solution 3 mgorzel
Solution 4 hemant singh