Menu
Coddy logo textTech

Grouping

Lesson 16 of 28 in Coddy's RegEx in Python course.

Grouping in regex is used to group parts of a pattern together. This is useful when you want to apply quantifiers to an entire group of characters or to capture parts of the match for later use.

import re

text = "The rain in Spain falls mainly in the plain."
pattern = r"(in\s\w+)"
matches = re.findall(pattern, text)

print(matches)  # Output: ['in Spain', 'in the', 'in the']

In the above example, the pattern (in\s\w+) groups the string "in" followed by a whitespace character and one or more word characters. The findall function returns a list of all matching groups.

challenge icon

Challenge

Easy

Write a function named find_repeated_phrases that takes a text string as input and returns a list of phrases that contain a word followed by an exclamation mark !.

Try it yourself

import re

def find_repeated_phrases(text):
    # Write code here

All lessons in RegEx in Python