Search code examples
pythonregex

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

  • 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))