github.com/jxgolibs/go-oauth2-server@v1.0.1/util/regex.go (about) 1 package util 2 3 import ( 4 "errors" 5 "regexp" 6 ) 7 8 var ( 9 // ErrNoMatchFound ... 10 ErrNoMatchFound = errors.New("No match found") 11 ) 12 13 // RegexExtractMatches extracts multiple named matches from a string using regex 14 func RegexExtractMatches(in, regExp string, names ...string) (map[string]string, error) { 15 compiledRegex, err := regexp.Compile(regExp) 16 if err != nil { 17 return map[string]string{}, err 18 } 19 20 subExpNames := compiledRegex.SubexpNames() 21 results := compiledRegex.FindAllStringSubmatch(in, -1) 22 23 if len(results) == 0 { 24 return map[string]string{}, ErrNoMatchFound 25 } 26 27 matches := make(map[string]string, len(names)) 28 for i, match := range results[0] { 29 for _, name := range names { 30 if subExpNames[i] == name { 31 matches[name] = match 32 } 33 } 34 } 35 36 return matches, nil 37 } 38 39 // RegexExtractMatch extracts a named match from a string using regex 40 func RegexExtractMatch(in, regularExpression, name string) (string, error) { 41 compiledRegex, err := regexp.Compile(regularExpression) 42 if err != nil { 43 return "", err 44 } 45 46 names := compiledRegex.SubexpNames() 47 results := compiledRegex.FindAllStringSubmatch(in, -1) 48 49 if len(results) == 0 { 50 return "", ErrNoMatchFound 51 } 52 53 for i, match := range results[0] { 54 if names[i] != name { 55 continue 56 } 57 58 return match, nil 59 } 60 61 return "", ErrNoMatchFound 62 }