How the pattern works
| Part | Meaning |
|---|---|
\b(\w+) | A whole word, captured as group 1 |
\s+ | Whitespace |
\1\b | Backreference: the same word again |
i flag | “The the” counts as a duplicate |
→ $1 | Replaced with a single copy |
Code examples
JavaScript
const out = text.replace(/\b(\w+)\s+\1\b/gi, "$1");Python
import re
out = re.sub(r'\b(\w+)\s+\1\b', r'\1', text, flags=re.I)PHP
$out = preg_replace('/\b(\w+)\s+\1\b/i', '$1', $text);
Notes and limitations
Great for proofreading. Some repeats are intentional (“had had”, “that that”), so review matches before replacing them all.
Regex TesterType a pattern and watch matches highlight live in your test text.
Open the tool Frequently asked questions
What is the regex to find duplicate words?
/\b(\w+)\s+\1\b/gi — it is used with find and replace. See the table above for what each part does.
Does it work in Python and PHP?
Yes — the code examples above use the same pattern with re in Python and preg functions in PHP.
How do I test this regex?
Click “Open in Regex Tester” — the pattern, flags and sample text load automatically, and matches highlight as you edit.