Skip to content

Instantly share code, notes, and snippets.

@eculver
Last active April 3, 2024 14:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eculver/d1338aa87e87890e05d4f61ed0a33d6e to your computer and use it in GitHub Desktop.
Save eculver/d1338aa87e87890e05d4f61ed0a33d6e to your computer and use it in GitHub Desktop.
Find all named match groups and return as a map keyed by the group name
// 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<year>\d{4})-(?P<month>\d{2})-(?P<day>\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
}
@eculver
Copy link
Author

eculver commented Oct 11, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment