Regex to find duplicate words

Use /\b(\w+)\s+\1\b/gi with find and replace. Every example below is tested against the pattern, and you can open it in the Regex Tester with the samples preloaded.

Updated

/\b(\w+)\s+\1\b/gi
Open in Regex Tester

Before

This is is a test of the the duplicate finder. The the end.

After (replace with "$1")

This is a test of the duplicate finder. The end.

How the pattern works

PartMeaning
\b(\w+)A whole word, captured as group 1
\s+Whitespace
\1\bBackreference: the same word again
i flag“The the” counts as a duplicate
→ $1Replaced 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.