ExistInSliceWithRegex checks whether a string exists in a slice either by direct match, or by a regular expression (eg. `^\w+$`). Note: Only list items starting with '^' and ending with '$' are treated as regular expressions!
(str string, list []string)
| 41 | // |
| 42 | // Note: Only list items starting with '^' and ending with '$' are treated as regular expressions! |
| 43 | func ExistInSliceWithRegex(str string, list []string) bool { |
| 44 | for _, field := range list { |
| 45 | isRegex := strings.HasPrefix(field, "^") && strings.HasSuffix(field, "$") |
| 46 | |
| 47 | if !isRegex { |
| 48 | // check for direct match |
| 49 | if str == field { |
| 50 | return true |
| 51 | } |
| 52 | continue |
| 53 | } |
| 54 | |
| 55 | // check for regex match |
| 56 | pattern := cachedPatterns.Get(field) |
| 57 | if pattern == nil { |
| 58 | var err error |
| 59 | pattern, err = regexp.Compile(field) |
| 60 | if err != nil { |
| 61 | continue |
| 62 | } |
| 63 | // "cache" the pattern to avoid compiling it every time |
| 64 | // (the limit size is arbitrary and it is there to prevent the cache growing too big) |
| 65 | // |
| 66 | // @todo consider replacing with TTL or LRU type cache |
| 67 | cachedPatterns.SetIfLessThanLimit(field, pattern, 500) |
| 68 | } |
| 69 | |
| 70 | if pattern != nil && pattern.MatchString(str) { |
| 71 | return true |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | return false |
| 76 | } |
| 77 | |
| 78 | // ToInterfaceSlice converts a generic slice to slice of interfaces. |
| 79 | func ToInterfaceSlice[T any](list []T) []any { |
searching dependent graphs…