Use (?P<name>pattern) syntax in Go regex and retrieve matches via SubexpIndex to access named groups.
Use named capture groups in Go by placing (?P<name>pattern) inside your regular expression string, then access the matched text via re.FindStringSubmatch and the group name index returned by re.SubexpIndex.
import "regexp"
re := regexp.MustCompile(`(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})`)
match := re.FindStringSubmatch("2023-10-25")
if match != nil {
year := match[re.SubexpIndex("year")]
month := match[re.SubexpIndex("month")]
day := match[re.SubexpIndex("day")]
// year="2023", month="10", day="25"
}
Named capture groups let you give a specific label to a part of a regular expression pattern so you can retrieve that matched text by name instead of remembering its position number. This makes your code easier to read and maintain because you refer to data like 'year' or 'month' directly rather than counting which slice index holds it. Think of it like labeling boxes in a moving truck so you know exactly where your kitchen items are without having to count every box.