Python Practice › RegEx Programs › Program 17
Find repeated words
Write a Python program to find accidentally repeated words like “the the”.
Output
['is', 'the', 'module'] This is a test of the regex module.
Approach
- A back-reference
\1matches the same text again.
Solution
import re text = "This is is a test of the the regex module module."print(re.findall(r"\b(\w+)\s+\1\b", text))print(re.sub(r"\b(\w+)\s+\1\b", r"\1", text))Output
['is', 'the', 'module'] This is a test of the regex module.
Learn the concept
New to this topic? Read the lesson, then come back.