regexhelper
Test a pattern. Copy a ready-made one. No signup.

Go's RE2 Regex — Limits and Workarounds

Go's regexp is RE2: fast and safe from catastrophic backtracking, but it rejects lookahead, lookbehind and backreferences. If a pattern that works in Python fails to compile in Go, this is usually why.

What RE2 does NOT support

FeatureRE2 / GoWorkaround
Lookahead (?=...) (?!...)NoRestructure; validate in Go code after matching
Lookbehind (?<=...)NoCapture the prefix in a group instead
Backreferences \1NoMatch candidates, compare equality in code
Atomic groups / possessive *+NoNot needed — RE2 has no catastrophic backtracking
Named groups (?P<n>)YesRead with SubexpNames()

Why the restrictions exist

RE2 guarantees that matching runs in time linear to the input length, so a hostile or accidental pattern can never hang your server (the "ReDoS" class of bugs). Lookaround and backreferences require backtracking, which can blow up exponentially — so RE2 leaves them out on purpose. It is a deliberate safety trade, not a missing feature.

Porting example

// A backreference pattern like (\w+)\s+\1 (repeated word) won't compile in Go.
// Match candidate pairs, then compare in code:
re := regexp.MustCompile(`(\w+)\s+(\w+)`)
m := re.FindStringSubmatch("the the cat")
if m != nil && m[1] == m[2] {
    // duplicate word found
}

Reading named groups in Go

re := regexp.MustCompile(`(?P<year>\d{4})-(?P<month>\d{2})`)
m := re.FindStringSubmatch("2026-09")
names := re.SubexpNames()   // ["", "year", "month"]
// m[1] is year, m[2] is month

FAQ

Why won't my lookahead compile in Go?

Go uses the RE2 engine, which does not support lookahead or lookbehind. Move that logic out of the regex — match the core text and validate the condition in Go code.

Does Go regexp support backreferences?

No. RE2 has no backreferences because they require backtracking. Capture the parts in separate groups and compare them in code instead.

Is there a Go regex library with lookahead?

The standard library will not add it, but third-party packages like dlclark/regexp2 port the .NET engine and support lookaround and backreferences at the cost of RE2's linear-time guarantee.