github.com/coveo/gotemplate@v2.7.7+incompatible/utils/regex.go (about) 1 package utils 2 3 import "regexp" 4 5 // MultiMatch returns a map of matching elements from a list of regular expressions (returning the first matching element) 6 func MultiMatch(s string, expressions ...*regexp.Regexp) (map[string]string, int) { 7 for i, re := range expressions { 8 if matches := re.FindStringSubmatch(s); len(matches) != 0 { 9 results := make(map[string]string) 10 for i, key := range re.SubexpNames() { 11 if key != "" { 12 results[key] = matches[i] 13 } 14 } 15 return results, i 16 } 17 } 18 return nil, -1 19 } 20 21 // GetRegexGroup cache compiled regex to avoid multiple interpretation of the same regex 22 func GetRegexGroup(key string, definitions []string) (result []*regexp.Regexp, err error) { 23 if result, ok := cachedRegex[key]; ok { 24 return result, nil 25 } 26 27 result = make([]*regexp.Regexp, len(definitions)) 28 for i := range definitions { 29 regex, err := regexp.Compile(definitions[i]) 30 if err != nil { 31 return nil, err 32 } 33 result[i] = regex 34 } 35 36 cachedRegex[key] = result 37 return 38 } 39 40 var cachedRegex = map[string][]*regexp.Regexp{}