Python Practice › RegEx Programs › Program 17

Find repeated words

EasyRegEx Programs · 17 of 20

Write a Python program to find accidentally repeated words like “the the”.

Advertisement
Output
['is', 'the', 'module']
This is a test of the regex module.

Approach

  1. A back-reference \1 matches the same text again.

Solution

Python
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.

More regex programs

← All 20 RegEx Programs

Leave a Comment