Thursday, September 6, 2018

Save the matched values into variables in golang regular expression

Save the matched values into variables in golang regular expression

package main

import (
 "fmt"
 "regexp"
)

func mapSubexpNames(m, n []string) map[string]string {
 m, n = m[1:], n[1:]
 r := make(map[string]string, len(m))
 for i, _ := range n {
  r[n[i]] = m[i]
 }
 return r
}

func main() {
 r := regexp.MustCompile(`(?P<Year>\d{4})-(?P<Month>\d{2})-(?P<Day>\d{2})`)
 m := r.FindStringSubmatch(`2015-05-27`)
 n := r.SubexpNames()
 fmt.Println(mapSubexpNames(m, n))
}

Reference:

https://stackoverflow.com/questions/30483652/how-to-get-capturing-group-functionality-in-golang-regular-expressions

No comments: