// FindAllGroups returns a map with each match group. The map key corresponds to the match group name. // A nil return value indicates no matches. func FindAllGroups(re *regexp.Regexp, s string) map[string]string { matches := re.FindStringSubmatch(s) subnames := re.SubexpNames() if matches == nil || len(matches) != len(subnames) { return nil } matchMap := map[string]string{} for i := 1; i < len(matches); i++ { matchMap[subnames[i]] = matches[i] } return matchMap, nil } func ExampleFindAllGroups() { re := regexp.MustCompile(`(?P\d{4})-(?P\d{2})-(?P\d{2})`) matchMap := FindAllGroups(re, "2018-10-11") for k, v := range matchMap { fmt.Printf("%s: %s\n", k, v) } // Output: // year: 2018 // month: 10 // day: 11 }