Skip to content

Instantly share code, notes, and snippets.

@RoryQ
Last active April 16, 2024 07:28
Show Gist options
  • Select an option

  • Save RoryQ/46d130cbc4c4f5d13c8ff70e83efe92c to your computer and use it in GitHub Desktop.

Select an option

Save RoryQ/46d130cbc4c4f5d13c8ff70e83efe92c to your computer and use it in GitHub Desktop.
package xregexp
import "regexp"
func FindMatchGroups(re *regexp.Regexp, s string) (map[string]string, bool) {
matches := re.FindStringSubmatch(s)
return getNamedMatches(re, matches), len(matches) > 0
}
func FindAllMatchGroups(re *regexp.Regexp, s string) ([]map[string]string, bool) {
matches := re.FindAllStringSubmatch(s, -1)
namedMatches := []map[string]string{}
for _, groups := range matches {
namedMatches = append(namedMatches, getNamedMatches(re, groups))
}
return namedMatches, len(matches) > 0
}
func getNamedMatches(re *regexp.Regexp, matches []string) map[string]string {
result := make(map[string]string)
for i, name := range re.SubexpNames() {
result[name] = matches[i]
}
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment