regex.go 656 B

123456789101112131415161718192021222324252627282930313233
  1. package openaicompat
  2. import (
  3. "regexp"
  4. "sync"
  5. )
  6. var compiledRegexCache sync.Map // map[string]*regexp.Regexp
  7. func matchAnyRegex(patterns []string, s string) bool {
  8. if len(patterns) == 0 || s == "" {
  9. return false
  10. }
  11. for _, pattern := range patterns {
  12. if pattern == "" {
  13. continue
  14. }
  15. re, ok := compiledRegexCache.Load(pattern)
  16. if !ok {
  17. compiled, err := regexp.Compile(pattern)
  18. if err != nil {
  19. // Treat invalid patterns as non-matching to avoid breaking runtime traffic.
  20. continue
  21. }
  22. re = compiled
  23. compiledRegexCache.Store(pattern, re)
  24. }
  25. if re.(*regexp.Regexp).MatchString(s) {
  26. return true
  27. }
  28. }
  29. return false
  30. }