Named Capture Group (Date) in GO
Demonstrate named capture groups by extracting year/month/day from ISO-style dates.
Try it in the GO tester →Pattern
regexGO
(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2}) (flags: g)Go (RE2) code
goGo
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})`)
input := `Born 1990-05-21, hired 2018-09-10`
for _, match := range re.FindAllString(input, -1) {
fmt.Println(match)
}
}Uses `regexp.MustCompile` (panics on bad patterns at startup) and `FindAllString` for all matches.
How the pattern works
(?<year>\d{4}) captures four digits under the name 'year'; (?<month>\d{2}) and (?<day>\d{2}) likewise. Modern JS, Python 3.7+, and Go (with `(?P<...>)` syntax — JS-style is also accepted in Python 3.12+) all support this; the matched substring is accessible by name in code (e.g. m.groups.year in JS, m['year'] in Python).
Examples
Input
Born 1990-05-21, hired 2018-09-10Matches
1990-05-212018-09-10
Input
Today is 2026-04-25Matches
2026-04-25
Input
no dates hereNo match
—