How to Use Named Capture Groups in Go

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"
}