Skip to main content
hank-builds.com

Duplicate Words regex

Finds consecutive duplicate words.

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

What it matches

A word, whitespace, then the same word again, matched with the backreference \1 and bounded at both ends so it cannot fire inside a longer word. The i flag makes it case-insensitive, which is what catches the sentence-boundary case where one line ends in "the" and the next begins with "The".

Railroad diagram

Read left to right. Every path through the diagram is a string the pattern accepts.

\b Group \w \s \1 \b

Drag to pan. Ctrl+scroll to zoom.

Breakdown

gFind all matches instead of stopping after the first
iLetters match both upper and lower case
\bWord boundary
\w+Word character (a-z, A-Z, 0-9, _), one or more
\s+Whitespace, one or more
\1Backreference to group #1
\bWord boundary

Test cases

Matches

  • the the
  • fox fox jumped
  • It is is broken

Does not match

  • the quick brown fox
  • hello world

Caveats

Some repetition is correct: "had had", "that that" and "is is" all appear in valid English. It only sees adjacent pairs, so "the quick the" is invisible. \w excludes apostrophes and accented letters, so it splits words like naïve and treats the halves separately.

More text processing patterns

Test this against your own input in the regex tester, browse the full pattern library, or check the syntax cheat sheet.