Regular expression for 12 hours time format

Viewed 4701

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
5 Answers
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

You should make the following changes:

  • Use a case insensitive search, pass re.I flag
  • Remove the space after $
  • You may return the boolean result by using bool(re.search(...))
  • To avoid the overhead related to capture group memory allocation, you may replace all your capturing groups to non-capturing ones ((...) -> (?:...)).

See Python code example:

def check_time(text):
  pattern = r"^(?:1[0-2]|0?[1-9]):(?:[0-5]?[0-9])(?:\s?[AP]M)?$"
  return bool(re.search(pattern, text, flags=re.I))
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
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
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

Related