github.com/safing/portbase@v0.19.5/database/query/condition-regex.go (about) 1 package query 2 3 import ( 4 "errors" 5 "fmt" 6 "regexp" 7 8 "github.com/safing/portbase/database/accessor" 9 ) 10 11 type regexCondition struct { 12 key string 13 operator uint8 14 regex *regexp.Regexp 15 } 16 17 func newRegexCondition(key string, operator uint8, value interface{}) *regexCondition { 18 switch v := value.(type) { 19 case string: 20 r, err := regexp.Compile(v) 21 if err != nil { 22 return ®exCondition{ 23 key: fmt.Sprintf("could not compile regex \"%s\": %s", v, err), 24 operator: errorPresent, 25 } 26 } 27 return ®exCondition{ 28 key: key, 29 operator: operator, 30 regex: r, 31 } 32 default: 33 return ®exCondition{ 34 key: fmt.Sprintf("incompatible value %v for string", value), 35 operator: errorPresent, 36 } 37 } 38 } 39 40 func (c *regexCondition) complies(acc accessor.Accessor) bool { 41 comp, ok := acc.GetString(c.key) 42 if !ok { 43 return false 44 } 45 46 switch c.operator { 47 case Matches: 48 return c.regex.MatchString(comp) 49 default: 50 return false 51 } 52 } 53 54 func (c *regexCondition) check() error { 55 if c.operator == errorPresent { 56 return errors.New(c.key) 57 } 58 return nil 59 } 60 61 func (c *regexCondition) string() string { 62 return fmt.Sprintf("%s %s %s", escapeString(c.key), getOpName(c.operator), escapeString(c.regex.String())) 63 }