Duplicate Word
Detects consecutive duplicate words using a backreference.
Try it in RegexPro →Available in
JavaScript / ECMAScript code
const re = new RegExp("\\b(\\w+)\\s+\\1\\b", "gi");
const input = "the the cat sat on the the mat";
const matches = [...input.matchAll(re)];
console.log(matches.map(m => m[0]));Uses `String.prototype.matchAll` for global iteration (Node 12+ / all modern browsers).
Python (re) code
import re
pattern = re.compile(r"\b(\w+)\s+\1\b", re.IGNORECASE)
input_text = "the the cat sat on the the mat"
for m in pattern.finditer(input_text):
print(m.group(0))Stdlib `re` module — no third-party dependency. Works on Python 3.6+.
Why it doesn't work in GO
Go's RE2 engine doesn't support backreferences (`\1`, `\2`, …) for the same linear-time reason.
Approach
Match the candidate substring with a single capture, then verify the duplication in code; or use JS / Python which both support backreferences.
Read the full guide →Workaround code in Go (RE2)
package main
import (
"fmt"
"regexp"
)
// RE2 doesn't support backreferences. The fix: capture the candidate
// substring once, then verify the duplication in Go code.
//
// Example: instead of `(\w+)\s+\1` (duplicate words), capture two
// adjacent words and compare them.
func main() {
re := regexp.MustCompile(`\b(\w+)\s+(\w+)\b`)
input := "the cat cat ran ran fast"
for _, m := range re.FindAllStringSubmatch(input, -1) {
if m[1] == m[2] { // the backreference equality, in code
fmt.Println(m[0])
}
}
}Capture the candidate substrings as separate groups, then compare them in Go code instead of via a backreference.
Pattern
\b(\w+)\s+\1\b (flags: gi)Raw source: \b(\w+)\s+\1\b
How it works
Examples
Input
the the cat sat on the the matMatches
the thethe the
Input
no duplicates hereNo match
—Common use cases
- •Proofreading
- •Content editors
- •Writing-quality linters
Related patterns
Word Boundary (Whole Word Match)
Text ProcessingMatch the whole word `cat` without matching it inside other words like `concatenate` or `category`.
Negative Lookahead
Text ProcessingUse negative lookahead `(?!...)` to match words that are NOT in a blocklist (here: log-level keywords).
Single-Line Comment (// or #)
Text ProcessingMatch single-line comments using either the `//` (C-family) or `#` (shell, Python, Ruby, YAML) marker.
Base64 String
Text ProcessingMatch Base64-encoded strings, including proper padding with = and == characters.
Related concepts
Word Boundaries: \b and \B
Concept\b matches the position between a word character and a non-word character. It keeps your regex from matching 'cat' inside 'concatenate.'
How to Replace Text Using Regex in JavaScript
How-toString.replace and String.replaceAll accept a regex. Use the g flag for multi-match replace, $1/$2 for capture references, and a function for complex logic.