breakitdown

Regex to find repeated words ("the the")

Answer

\b(\w+)\s+\1\b with the gi flags finds a word followed by whitespace and the same word again. \1 is a backreference: it matches exactly the text that group 1 captured. Replace with $1 to remove the duplicate.

flags: g all matches · i ignore case · m ^ $ per line · s . matches newlines · u Unicode

JavaScript ✓PCRE ✓

No catastrophic-backtracking patterns found. (A heuristic check: nested and adjacent repeats, overlapping alternatives.)

  1. \bA word boundary: the edge between a word character and a non-word character (or the string's start or end)anchor
  2. (…)Capturing group #1: remembers what it matchedgroup
  3. \wA word character: a letter, digit or underscore (A-Z, a-z, 0-9, _)character type
  4. +Repeat it one or more times, as many as possible (greedy)quantifier
  5. \sA whitespace character (space, tab, line break and other Unicode spaces)character type
  6. +Repeat it one or more times, as many as possible (greedy)quantifier
  7. \1Backreference: the exact text that group #1 matchedbackreference
  8. \bA word boundary: the edge between a word character and a non-word character (or the string's start or end)anchor

1 capturing group.

Examples

Checked at build time in JavaScript and in Python's re.

InputMatches?
the the cat✓ match
The the cat✓ match
this is is fine✓ match
the cat✗ no match
the theory✗ no match
end end✓ match
that that's it✓ match
bye-bye✗ no match

Try your own text

One string per line: each line is tested on its own (the m flag is added here).

How it works

Group 1 captures a whole word, since \b forces the match to start at a word boundary. \s+ allows any whitespace between the two copies, including a line break, which is where doubled words usually hide in edited text. The final \b stops the theory from matching: after the comes o, a word character, so there is no boundary.

With the i flag, the backreference compares case-insensitively in both JavaScript and Python, so The the matches. s.replace(/\b(\w+)\s+\1\b/gi, "$1") keeps the first copy.

Variants

Gotchas

Related explainers

← Explain any regular expression