How to Match a String Against a Regex in Go

Use regexp.MatchString to verify if a string matches a regular expression pattern in Go.

Use regexp.MatchString to check if a string matches a pattern, returning a boolean result.

import "regexp"

matched, err := regexp.MatchString(`^\d{3}-\d{2}-\d{4}$`, "123-45-6789")
if err != nil {
    // handle error
}
// matched is true if the string fits the pattern

Alternatively, compile the pattern once for repeated use with regexp.Compile and call .MatchString on the resulting *regexp.Regexp.