Day 35 - Using Regular Expressions to Recognize User Input

We will introduce regular expressions and create a function that can recognize a variety of different data formats.

Finished Code

import re

def iI (strInput):

    patterns = {
        "Phone Number": r"^\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}$",
        "ZIP Code": r"^\d{5}(-\d{4})?$",
        "Email Address": r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$",
        "Time (12h or 24h)": r"^(0?[1-9]|1[0-2]):[0-5][0-9]\s?(AM|PM)$|^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$"
    }

    for label, pattern in patterns.items():
        if re.match(pattern, strInput):
            return f"Your pattern matches a {label}"

    return "Sorry, I couldn't find a match."

while True:

    strText = input("Enter a string and I will guess what it is: ")
    print("\n")

    print(iI(strText))
    print("\n\n")