Skip to content

Instantly share code, notes, and snippets.

@eculver

eculver/regex-utils.go

Last active Oct 11, 2018
Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

@eculver eculver commented Oct 11, 2018

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