RRegexBuilder
Get RegexBuilder

RegexBuilder · regex answers

Regex to find duplicate consecutive words

/\b(\w+)\s+\1\b/gi

\1 is a backreference: it matches whatever group 1 captured, not the pattern again. That is what makes 'the the' a match and 'the cat' not. Backreferences are the classic proof that regex engines are more than regular languages.

What each part does

\ba word boundary so partial words do not start a match
(\w+)capture a word into group 1
\s+the whitespace between them
\1the same text as group 1, repeated

Tested against real input

Every row below was run through the engine when this page was built. The third column is the substring the pattern actually matched.

InputResultMatched
the the catmatchesthe the
It is is finematchesis is
Word wordmatchesWord word
the catno match
the theatreno match

The mistake to avoid

Writing \1 in the replacement string when your language expects $1 there. Inside the pattern it is \1; in most replacement strings it is $1.

Try it on your own text

Paste this pattern and your input, see each match highlighted with its capture groups, step through what the engine did, and get the equivalent syntax for JavaScript, Python, Java, Go and PCRE.

Open RegexBuilder

Other regex answers