Go

regexp.MustCompile + FindAll

admin by @admin ADMIN
2h ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`regexp.MustCompile` panics on a bad pattern at startup — perfect for package-level vars. Use `Find`, `FindString`, `FindAllStringSubmatch` to extract matches and capture groups.
Go
Raw
package main

import (
    "fmt"
    "regexp"
)

// Compile once at startup — these are expensive to construct
var (
    emailRe = regexp.MustCompile(`[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}`)
    keyValRe = regexp.MustCompile(`(\w+)=(\w+)`)
)

func main() {
    text := "Contact alice@example.com or bob@x.io. Stripe key sk_live=abc123."

    // Find all matches as a flat slice
    emails := emailRe.FindAllString(text, -1)
    fmt.Println(emails)                          // [alice@example.com bob@x.io]

    // Capture groups via FindAllStringSubmatch
    matches := keyValRe.FindAllStringSubmatch(text, -1)
    for _, m := range matches {
        fmt.Printf("key=%s value=%s\n", m[1], m[2])
        // key=sk_live value=abc123
    }

    // Replace with backrefs ($1, $2, ...)
    out := keyValRe.ReplaceAllString(text, "$1=REDACTED")
    fmt.Println(out)
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.