Created
October 14, 2012 19:28
-
-
Save marcinwyszynski/3889572 to your computer and use it in GitHub Desktop.
Named captures in Go
This file contains 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 GetNamedMatches(exp *regexp.Regexp, | |
src string, limit int) map[string][]interface{} { | |
result := make(map[string][]interface{}) | |
matches := exp.FindAllStringSubmatch(src, limit) | |
groups := exp.SubexpNames() | |
for _, match := range matches { | |
for pos, val := range match { | |
fieldName := groups[pos] | |
if fieldName == "" { | |
continue | |
} | |
_, ok := result[fieldName] | |
if !ok { | |
result[fieldName] = make([]interface{}, 0) | |
} | |
result[fieldName] = append(result[fieldName], val) | |
} | |
} | |
return result | |
} | |
func main() { | |
exp := regexp.MustCompile("^/(?P<address>(?P<resource>\\w+)/(?P<id>[\\d]+))/(?P<action>[\\w]+)$") | |
src := "/products/13/view" | |
fmt.Printf("%+v\n", GetNamedMatches(exp, src, 2)) | |
format := "(?P<resource>/(?P<kind>\\w+)/(?P<id>\\d+))" | |
exp2 := regexp.MustCompile(format) | |
src2 := "/books/13/rentals/6" | |
fmt.Printf("%+v\n", GetNamedMatches(exp2, src2, 2)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment