Created
April 16, 2020 14:56
-
-
Save klingtnet/7473fcf8d33e7f339da22d1fa1c12862 to your computer and use it in GitHub Desktop.
Golang map of a regular experssions capture groups
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"]) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://play.golang.org/p/5SBBQRVuTWj