How to Compile a Regex Pattern in Go

Use regexp.Compile to parse a pattern into a reusable object, handling errors for invalid syntax.

Use regexp.Compile to parse a pattern string into a *regexp.Regexp object, checking the returned error for syntax issues.

re, err := regexp.Compile(`^\d{3}-\d{2}-\d{4}$`)
if err != nil {
    log.Fatal(err)
}

If the pattern is constant and known at compile time, use regexp.MustCompile to panic on error instead of returning it.

re := regexp.MustCompile(`^\d{3}-\d{2}-\d{4}$`)