How to Use Capture Groups in Go Regex

Use parentheses in Go regex patterns and access captured substrings via the Submatch slice returned by FindStringSubmatch.

Use parentheses in your regex pattern to define capture groups, then access the matched substrings via the Submatch method on the result of regexp.FindStringSubmatch.

import "regexp"

re := regexp.MustCompile(`(\w+)@(\w+)\.(\w+)`)
match := re.FindStringSubmatch("user@example.com")
if match != nil {
    fmt.Println(match[1]) // "user"
    fmt.Println(match[2]) // "example"
    fmt.Println(match[3]) // "com"
}