Skip to content

Instantly share code, notes, and snippets.

@skyjia
Created July 15, 2020 06:39
Show Gist options
  • Save skyjia/a727df89b2473c5b83b18da696804e51 to your computer and use it in GitHub Desktop.
Save skyjia/a727df89b2473c5b83b18da696804e51 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"regexp"
)
func main() {
e := `^(?P<length>\d+)(?P<unit>[dmy])$`
r := regexp.MustCompile(e)
names := r.SubexpNames()
tests := []string{
`1234d`,
`2y`,
`234m`,
`1234`,
`mmmm`}
for _, t := range tests {
fmt.Printf("testing: %q\r\n", t)
result := r.FindAllStringSubmatch(t, -1)
matched := r.MatchString(t)
fmt.Println("matched:", matched)
if result != nil {
m := map[string]string{}
for i, n := range result[0] {
m[names[i]] = n
}
fmt.Printf("<length>: %q\r\n", m["length"])
fmt.Printf("<unit>: %q\r\n", m["unit"])
}
fmt.Println()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment