Accessing Match Groups in Python Regex Without Match Object

I love the assignment expression trick! But what if we have a ton of patterns to match? Instead of manually checking each one, let’s use a dictionary to keep things DRY (Don’t Repeat Yourself)!"

import re

patterns = {
    r"I love (\w+)": "He loves",
    r"Ich liebe (\w+)": "Er liebt",
    r"Je t'aime (\w+)": "Il aime"
}

statements = ["I love Mary", "Ich liebe Margot", "Je t'aime Marie", "Te amo Maria"]

for statement in statements:
    for pattern, phrase in patterns.items():
        if m := re.match(pattern, statement):
            print(phrase, m.group(1))
            break
    else:
        print("???")

:bulb: Why is this great?

  • Easily extendable for more patterns.
  • Removes repetitive if-elif blocks.
  • Still uses assignment expressions for efficiency.
  • Keeps Python regex match group extraction smooth.