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
| \b | a word boundary so partial words do not start a match |
| (\w+) | capture a word into group 1 |
| \s+ | the whitespace between them |
| \1 | the 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.
| Input | Result | Matched |
|---|---|---|
| the the cat | matches | the the |
| It is is fine | matches | is is |
| Word word | matches | Word word |
| the cat | no match | — |
| the theatre | no 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 RegexBuilderOther regex answers
- Regex for an email address
- Regex for a US phone number
- Regex for an IPv4 address
- Regex for a URL
- Regex for a date in YYYY-MM-DD format
- Regex to match digits only
- Regex for alphanumeric characters
- Regex to find special characters
- Regex for a strong password
- Regex to match whitespace
- Regex to trim leading and trailing whitespace
- Regex for a UUID