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"
}
Capture groups let you isolate specific parts of a text match, like pulling just the username from an email address. Think of them as labeled buckets that catch specific pieces of information as the regex scans through the string. You use them whenever you need to extract data rather than just checking if a pattern exists.