๐Ÿ”ŽRegular ExpressionsLESSON

Regular Expressions

Go's regexp package provides RE2-syntax regular expressions โ€” compiled patterns that match strings, extract groups, and perform substitutions.

Compiling a pattern

Always compile patterns at package level with regexp.MustCompile โ€” panics at startup if the pattern is invalid, which is the right trade-off for a literal pattern:

Use regexp.Compile (returns error) when the pattern comes from user input:

Compiled *regexp.Regexp values are safe for concurrent use.

Matching

Finding matches

Capture groups

FindAllStringSubmatch returns all matches, each as a []string.

Named groups

Replace

Split

Performance tips

  • Compile once, reuse: *regexp.Regexp is goroutine-safe after compilation. Never compile inside a loop or hot path.
  • Use strings for simple cases: strings.Contains, strings.HasPrefix, strings.TrimSpace are 10โ€“100ร— faster than regex for fixed strings.
  • POSIX vs RE2: Go's regexp package uses RE2 syntax (no lookaheads/lookbehinds) โ€” all matches run in linear time, preventing catastrophic backtracking.

Knowledge Check

When should you use regexp.MustCompile instead of regexp.Compile?

What does FindStringSubmatch return for a pattern with capture groups?

Why does Go's regexp package not support lookaheads or lookbehinds?