You could create a little class that returns the boolean result of calling match, and retains the matched groups for subsequent retrieval:

import re

class REMatcher(object):
    def __init__(self, matchstring):
        self.matchstring = matchstring

    def match(self,regexp):
        self.rematch = re.match(regexp, self.matchstring)
        return bool(self.rematch)

    def group(self,i):
        return self.rematch.group(i)


for statement in ("I love Mary", 
                  "Ich liebe Margot", 
                  "Je t'aime Marie", 
                  "Te amo Maria"):

    m = REMatcher(statement)

    if m.match(r"I love (\w+)"): 
        print "He loves",m.group(1) 

    elif m.match(r"Ich liebe (\w+)"):
        print "Er liebt",m.group(1) 

    elif m.match(r"Je t'aime (\w+)"):
        print "Il aime",m.group(1) 

    else: 
        print "???"

Update for Python 3 print as a function, and Python 3.8 assignment expressions - no need for a REMatcher class now:

import re

for statement in ("I love Mary",
                  "Ich liebe Margot",
                  "Je t'aime Marie",
                  "Te amo Maria"):

    if m := re.match(r"I love (\w+)", statement):
        print("He loves", m.group(1))

    elif m := re.match(r"Ich liebe (\w+)", statement):
        print("Er liebt", m.group(1))

    elif m := re.match(r"Je t'aime (\w+)", statement):
        print("Il aime", m.group(1))

    else:
        print()
Answer from PaulMcG on Stack Overflow
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ python_regex.asp
Python RegEx
RegEx can be used to check if a string contains the specified search pattern. Python has a built-in package called re, which can be used to work with Regular Expressions.
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ gloss_python_regex_match.asp
Python RegEx Match Object
import re txt = "The rain in Spain" x = re.search(r"\bS\w+", txt) print(x.group()) Try it Yourself ยป ยท Note: If there is no match, the value None will be returned, instead of the Match Object. Python RegEx Tutorial RegEx RegEx Functions Metacharacters in RegEx RegEx Special Sequences RegEx Sets ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com
๐ŸŒ
W3Schools
w3schools.in โ€บ python โ€บ regular-expressions
Python Regular Expressions - W3Schools
import re list = [ "mouse", "cat", "dog", "no-match"] # Loop starts here for elements in list: m = re.match("(d\w+) \W(d/w+)" , element) # Check for matching if m: print (m . groups ( ))
๐ŸŒ
Google
developers.google.com โ€บ google for education โ€บ python โ€บ python regular expressions
Python Regular Expressions | Python Education | Google for Developers
Then the if-statement tests the match -- if true the search succeeded and match.group() is the matching text (e.g. 'word:cat'). Otherwise if the match is false (None to be more specific), then the search did not succeed, and there is no matching text. The 'r' at the start of the pattern string designates a python "raw" string which passes through backslashes without change which is very handy for regular expressions (Java needs this feature badly!).
๐ŸŒ
Imperial College London
python.pages.doc.ic.ac.uk โ€บ 2021 โ€บ lessons โ€บ regex โ€บ 07-groups โ€บ 01-group.html
Ic
>>> pattern = "Name: ([A-Za-z ]+); Phone: (\d+); Position: (.+)" >>> string = "Name: Josiah Wang; Phone: 012345678; Position: Senior Teaching Fellow" >>> match = re.match(pattern, string) >>> print(match) <re.Match object; span=(0, 69), match='Name: Josiah Wang; Phone: 012345678; Position: Se> >>> match.groups() ('Josiah Wang', '012345678', 'Senior Teaching Fellow') >>> match.group() 'Name: Josiah Wang; Phone: 012345678; Position: Senior Teaching Fellow' >>> match.group(1) 'Josiah Wang' >>> match.group(2) '012345678' >>> match.group(3) 'Senior Teaching Fellow' >>> match.group(1,3) ('Josiah Wang', 'Senior Teaching Fellow') >>> match.start(), match.end() (0, 69) >>> match.start(1), match.end(1) (6, 17) >>> match.start(2), match.end(2) (26, 35) >>> match.start(3), match.end(3) (47, 69) >>> match.span(2) # another way of getting a tuple (start, end) (26, 35) >>> match.span(3) (47, 69)
Top answer
1 of 5
78

You could create a little class that returns the boolean result of calling match, and retains the matched groups for subsequent retrieval:

import re

class REMatcher(object):
    def __init__(self, matchstring):
        self.matchstring = matchstring

    def match(self,regexp):
        self.rematch = re.match(regexp, self.matchstring)
        return bool(self.rematch)

    def group(self,i):
        return self.rematch.group(i)


for statement in ("I love Mary", 
                  "Ich liebe Margot", 
                  "Je t'aime Marie", 
                  "Te amo Maria"):

    m = REMatcher(statement)

    if m.match(r"I love (\w+)"): 
        print "He loves",m.group(1) 

    elif m.match(r"Ich liebe (\w+)"):
        print "Er liebt",m.group(1) 

    elif m.match(r"Je t'aime (\w+)"):
        print "Il aime",m.group(1) 

    else: 
        print "???"

Update for Python 3 print as a function, and Python 3.8 assignment expressions - no need for a REMatcher class now:

import re

for statement in ("I love Mary",
                  "Ich liebe Margot",
                  "Je t'aime Marie",
                  "Te amo Maria"):

    if m := re.match(r"I love (\w+)", statement):
        print("He loves", m.group(1))

    elif m := re.match(r"Ich liebe (\w+)", statement):
        print("Er liebt", m.group(1))

    elif m := re.match(r"Je t'aime (\w+)", statement):
        print("Il aime", m.group(1))

    else:
        print()
2 of 5
33

Less efficient, but simpler-looking:

m0 = re.match("I love (\w+)", statement)
m1 = re.match("Ich liebe (\w+)", statement)
m2 = re.match("Je t'aime (\w+)", statement)
if m0:
  print("He loves", m0.group(1))
elif m1:
  print("Er liebt", m1.group(1))
elif m2:
  print("Il aime", m2.group(1))

The problem with the Perl stuff is the implicit updating of some hidden variable. That's simply hard to achieve in Python because you need to have an assignment statement to actually update any variables.

The version with less repetition (and better efficiency) is this:

pats = [
    ("I love (\w+)", "He Loves {0}" ),
    ("Ich liebe (\w+)", "Er Liebe {0}" ),
    ("Je t'aime (\w+)", "Il aime {0}")
 ]
for p1, p3 in pats:
    m = re.match(p1, statement)
    if m:
        print(p3.format(m.group(1)))
        break

A minor variation that some Perl folk prefer:

pats = {
    "I love (\w+)" : "He Loves {0}",
    "Ich liebe (\w+)" : "Er Liebe {0}",
    "Je t'aime (\w+)" : "Il aime {0}",
}
for p1 in pats:
    m = re.match(p1, statement)
    if m:
        print(pats[p1].format(m.group(1)))
        break

This is hardly worth mentioning except it does come up sometimes from Perl programmers.

๐ŸŒ
PYnative
pynative.com โ€บ home โ€บ python โ€บ regex โ€บ python regex capturing groups
Python Regex Capturing Groups โ€“ PYnative
April 12, 2021 - We create a group by placing the regex pattern inside the set of parentheses ( and ) . For example, the regular expression (cat) creates a single group containing the letters โ€˜cโ€™, โ€˜aโ€™, and โ€˜tโ€™. For example, in a real-world case, you want to capture emails and phone numbers, So you ...
๐ŸŒ
Python documentation
docs.python.org โ€บ 3 โ€บ howto โ€บ regex.html
Regular Expression HOWTO โ€” Python 3.14.3 documentation
Author, A.M. Kuchling ,. Abstract: This document is an introductory tutorial to using regular expressions in Python with the re module. It provides a gentler introduction than th...
Find elsewhere
๐ŸŒ
w3resource
w3resource.com โ€บ python โ€บ python-regular-expression.php
Python Regular Expression
# group reference ``(?P<name>...)`` >>> import re >>> pattern = '(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})' >>> mon = re.search(pattern, '2018-09-01') >>> mon.group('year') '2018' >>> mon.group('month') '09' >>> mon.group('day') '01' # back reference ``(?P=name)`` >>> import re >>> re.search('^(?P<char>[a-z])(?P=char)','aa') <_sre.SRE_Match object at 0x01A08660>
๐ŸŒ
Spark By {Examples}
sparkbyexamples.com โ€บ home โ€บ python โ€บ python regex groups
Python regex groups - Spark By {Examples}
May 31, 2024 - The syntax for creating groups ... specific information from text. So to create a regex group simply enclose the desired pattern within parentheses ( )....
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ What-is-the-groups-method-in-regular-expressions-in-Python
What is the groups() method in regular expressions in Python?
The match.group() function in Python's re module is used to get the captured groups after a successful regular expression match. When a regular expression uses parentheses, it creates capturing groups with the matched substrings. The match.group() method returns the captured substrings.
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ gloss_python_regex_functions.asp
Python RegEx Functions
Python RegEx Tutorial RegEx Metacharacters in RegEx RegEx Special Sequences RegEx Sets RegEx Match Object ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ gloss_python_regex_sequences.asp
Python RegEx Special Sequences
Python RegEx Tutorial RegEx RegEx Functions Metacharacters in RegEx RegEx Sets RegEx Match Object ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com
๐ŸŒ
Python Tutorial
pythontutorial.net โ€บ home โ€บ python regex โ€บ python regex capturing group
Python Regex Capturing Groups
February 18, 2022 - For example, to create a capturing group that captures the id from the path, you use the following pattern: ... In this pattern, we place the rule \d+ inside the parentheses (). If you run the program with the new pattern, youโ€™ll see that it displays one match: import re s = 'news/100' pattern = '\w+/(\d+)' matches = re.finditer(pattern, s) for match in matches: print(match)Code language: Python (python)
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ re-matchobject-group-function-in-python-regex
re.MatchObject.group() function in Python Regex - GeeksforGeeks
July 15, 2025 - re.MatchObject.group() method returns the complete matched subgroup by default or a tuple of matched subgroups depending on the number of arguments
๐ŸŒ
Wellsr
wellsr.com โ€บ python โ€บ using-python-regex-groups-to-capture-substrings
Using Python Regex Groups to Capture Substrings - wellsr.com
June 28, 2019 - This tutorial describes how to use Python Regex Groups to capture a substring or submatch, and it describes how to refer to a group's substring inside a regex.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ how-do-we-use-python-regular-expression-named-groups
How do we use Python Regular Expression named groups?
Following is the Python example, which demonstrates how to match a particular pattern in a string using groups - import re input_string = "Tutorials Point began as a single HTML tutorial and has since expanded to offer a wide range of online courses and tutorials. It was established on 2014-06-12." regexp = r"(\d{4})-(\d{2})-(\d{2})" match = re.search(regexp, input_string) if match: print("Found date in the given text:", match.group(0)) print("Year:", match.group(1)) print("Month:", match.group(2)) print("Day:", match.group(3))
๐ŸŒ
Note.nkmk.me
note.nkmk.me โ€บ home โ€บ python
How to Use Regex Match Objects in Python | note.nkmk.me
May 18, 2023 - However, be aware that some regex patterns may match a zero-length string (empty string ''), which is still evaluated as True. m = re.match('[0-9]*', s) print(m) # <re.Match object; span=(0, 0), match=''> print(m.group() == '') # True print(bool(m)) # True if re.match('[0-9]*', s): print('match') else: print('no match') # match