Duplicate Word in GO
Go (RE2) can't run this pattern out of the box.
Try it in the GO tester →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.
Workaround code in Go (RE2)
goGo (workaround)
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
regexGO
\b(\w+)\s+\1\b (flags: gi)How the pattern works
`\b(\w+)\b` captures a word. `\s+\1\b` matches whitespace followed by the same word (backreference `\1`). Case-insensitive.
Examples
Input
the the cat sat on the the matMatches
the thethe the
Input
no duplicates hereNo match
—