In this article, you will learn how to capture regex groups in Python. Capturing groups let you match several distinct parts of a pattern in the same target string and extract each part separately.
Also, Solve:
Table of contents
What is a group in regex?
A group is a part of a regex pattern enclosed in parentheses (). For example, the regular expression (cat) creates a single group containing the letters ‘c’, ‘a’, and ‘t’.
Groups do two jobs:
- Capture: The text matched by each group is saved, so you can extract it from the Match object. For example, one group can capture a username and another can capture a domain from an email address.
- Treat several characters as one unit: A quantifier after a group applies to the whole group. For example,
(ab)+matches “ab”, “abab”, “ababab”, and so on.
Groups are numbered by counting their opening parentheses from left to right. For example, the expression ((\w)(\s\d)) contains three groups:
((\w)(\s\d))(\w)(\s\d)
Output:
a 1 a 1
Note:
Anything in parentheses () is a capturing group (unless it starts with ?:, see non-capturing groups). Use the group(group_number) method of the Match object to get the text matched by each group.
Example: Capture multiple groups
Suppose you have the following string:
target_string = "The price of PINEAPPLE ice cream is 20"Code language: Python (python)
You want to extract two values from it: the uppercase word (PINEAPPLE) and the number (20). For that, you need two group patterns.
Group 1: an uppercase word: \b[A-Z]+\b
[A-Z]is a character class that matches any capital letter from A to Z.- The
+metacharacter means one or more of them. \bis a word boundary, so the match must be a whole word. Without it, “T” in “The” would match.
Group 2: a number: \d+
\dmatches any digit from 0 to 9.+means the number has one or more digits.
Between the two groups we put .+. The dot matches any character except a newline, and + repeats it, so .+ skips over the text between the word and the number (” ice cream is “). This part is not in parentheses, so it is matched but not captured.
Output:
('PINEAPPLE', '20')
PINEAPPLE
20
- We used a raw string (
r"...") for the pattern so that Python does not treat backslashes such as\bas escape sequences. - The parentheses are not part of the text being matched. They only mark the groups.
re.search()returns the first match, and itsgroups()method returns all captured groups as a tuple.
Access each group result separately
Pass a group number to group() to get the text matched by that group. Unlike string indexing, group numbering starts at 1.
Group 0 is special: it is the entire match (not the entire target string). Calling group() with no argument is the same as group(0).
Output:
PINEAPPLE 20 PINEAPPLE ice cream is 20 PINEAPPLE ice cream is 20
Asking for a group number that doesn’t exist, such as result.group(3) here, raises IndexError: no such group.
Capture a group multiple times
re.search() returns only the first match. If the string contains several matches and you want the groups of every one, use the finditer() method. It returns an iterator of Match objects, and you can call group() on each one.
Output:
PINEAPPLE -> 20 MANGO -> 30 CHOCOLATE -> 40
findall() with groups
findall() also works with groups, but it returns plain strings and tuples instead of Match objects, so you can’t call group() on the result. Its behavior depends on the number of groups:
- No groups: a list of the full matches.
- One group: a list of that group’s matches only.
- Two or more groups: a list of tuples, one tuple per match.
Output:
['PINEAPPLE 20', 'MANGO 30', 'CHOCOLATE 40']
['20', '30', '40']
[('PINEAPPLE', '20'), ('MANGO', '30'), ('CHOCOLATE', '40')]
Extract a range of group matches
You can pass several group numbers to group() to get those groups back as a tuple. For example, group(1, 3) returns groups 1 and 3.
Output:
('Jessa', '28')
('Jessa', 'Data Engineer', 'Berlin')
Named groups
Group numbers are hard to read in long patterns and break when you add a new group. Instead, you can give a group a name with the syntax (?P<name>...) and access it by that name.
match.group("name")returns the text of one named group.match["name"]is a shortcut for the same thing.match.groupdict()returns all named groups as a dictionary.
Output:
jessa.watson
example.com
{'user': 'jessa.watson', 'domain': 'example.com'}
jessa.watson
Non-capturing groups
Sometimes you need parentheses only to group a part of the pattern, for example to apply a quantifier or alternation (|), but you don’t want to capture it. Use (?:...) for a non-capturing group. It groups like normal parentheses but doesn’t create a group number, which keeps groups() and findall() results clean.
Output:
['USD', 'EUR'] ['20 USD', '35 EUR']
Optional groups and default values
If a group is optional (followed by ?) and doesn’t take part in the match, group() returns None for it. Pass a default value to groups() or groupdict() to use something else instead of None.
Output:
('3', '12', None)
('3', '12', 'stable')
Backreferences
A captured group can be reused later in the same pattern. \1 refers to the text matched by group 1, \2 to group 2, and so on. For a named group, use (?P=name). This is useful for finding repeated text.
Example: Find words that are accidentally repeated
Output:
['is', 'the'] This is a test of the regex
Learn more about using groups in replacements in Python regex replace using re.sub().
Summary
- Parentheses
()create a capturing group. Groups are numbered from 1, by their opening parenthesis, from left to right. group(n)returns one group,group(0)orgroup()returns the entire match, andgroups()returns all groups as a tuple.- Use
finditer()to get the groups of every match.findall()returns tuples when the pattern has more than one group. (?P<name>...)creates a named group, andgroupdict()returns all named groups.(?:...)groups without capturing.\1(or(?P=name)) matches the same text that a group already captured.
Previous:
Next:
