Understand RE2 syntax limitations
Understand RE2 syntax limitations
Go regexp accepts RE2-style syntax (with documented Go-specific differences). Its matching time is guaranteed linear in input size for a fixed compiled expression. Backreferences and lookaround assertions are not supported. Linear matching does not mean every pattern is cheap to compile or that collecting unlimited results is safe.
package main
import ( "fmt" "regexp")
func main() { for _, p := range []string{`(a)\1`, `a(?=b)`, `a(b|c)`} { _, e := regexp.Compile(p) fmt.Println(e == nil) }}The first pattern requests a backreference and the second a lookahead. Both fail at compilation; the third uses supported alternation. For a requirement involving equal fields, capture both fields and compare the strings in ordinary Go code. Do not silently switch engines without reviewing their performance and semantics.
Expected output:
falsefalsetrueUse literal search and explicit validation
package main
import ( "fmt" "regexp")
func main() { r := regexp.MustCompile(`^([a-z]+):([a-z]+)$`) for _, s := range []string{"tea:tea", "tea:rice"} { m := r.FindStringSubmatch(s) fmt.Println(m != nil && m[1] == m[2]) } fmt.Println(regexp.MustCompile(regexp.QuoteMeta("a.b")).MatchString("axb"))}Short-circuit evaluation protects the capture indexing when there is no match. QuoteMeta escapes regex metacharacters when a literal must be inserted into a larger regex; for a simple literal search, use strings.Contains. It does not escape HTML or validate arbitrary input. Keep maximum input, pattern and result sizes explicit.
Expected output:
truefalsefalseTry it locally
Use QuoteMeta to compile a regex matching the literal a+b; print results for a+b and aaab.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Text processing 04: Understand RE2 syntax limitations
Check the lesson objective before moving on.
Which syntax is not supported by Go regexp?
What is a good way to enforce equal captured fields?