Skip to content

Instantly share code, notes, and snippets.

@klingtnet
Created April 16, 2020 14:56
Show Gist options
  • Save klingtnet/7473fcf8d33e7f339da22d1fa1c12862 to your computer and use it in GitHub Desktop.
Save klingtnet/7473fcf8d33e7f339da22d1fa1c12862 to your computer and use it in GitHub Desktop.
Golang map of a regular experssions capture groups
package main
import (
"fmt"
"regexp"
)
func capturingGroups(re *regexp.Regexp, input string) map[string]string {
groups := make(map[string]string)
matches := re.FindStringSubmatch(input)
for idx, name := range re.SubexpNames() {
groups[name] = matches[idx]
}
return groups
}
func main() {
exampleRE := regexp.MustCompile(`My name is (?P<firstname>\w+)\s(?P<lastname>\w+)`)
groups := capturingGroups(exampleRE, "My name is John Doe.")
fmt.Println(groups["lastname"], groups["firstname"])
}
@klingtnet
Copy link
Author

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