Skip to content

Commit

Permalink
add regular expression comparator
Browse files Browse the repository at this point in the history
  • Loading branch information
huttotw committed Jul 31, 2019
1 parent 4d0207e commit e7231e7
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 0 deletions.
25 changes: 25 additions & 0 deletions comparators.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package grules

import "regexp"

// Comparator is a function that should evaluate two values and return
// the true if the comparison is true, or false if the comparison is
// false
Expand Down Expand Up @@ -126,6 +128,29 @@ func greaterThanEqual(a, b interface{}) bool {
}
}

func regex(a, b interface{}) bool {
switch a.(type) {
case string:
at, ok := a.(string)
if !ok {
return false
}
bt, ok := b.(string)
if !ok {
return false
}

r, err := regexp.Compile(bt)
if err != nil {
return false
}

return r.MatchString(at)
default:
return false
}
}

// contains will return true if a contains b. We assume
// that the first interface is a slice. If you need b to be a slice
// consider using oneOf
Expand Down
29 changes: 29 additions & 0 deletions comparators_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,35 @@ func BenchmarkGreaterThanEqual(b *testing.B) {
}
}

func TestRegex(t *testing.T) {
cases := []testCase{
testCase{args: []interface{}{"a", "a"}, expected: true},
testCase{args: []interface{}{"a", "[ab]"}, expected: true},
testCase{args: []interface{}{"c", "[ab]"}, expected: false},
testCase{args: []interface{}{"abc", "c$"}, expected: true},
testCase{args: []interface{}{float64(1), float64(1)}, expected: false},
}

for i, c := range cases {
res := regex(c.args[0], c.args[1])
if res != c.expected {
t.Fatalf("expected case %d to be %v, got %v", i, c.expected, res)
}
}
}

func BenchmarkRegex(b *testing.B) {
for i := 0; i < b.N; i++ {
regex("a", "a")
}
}

func BenchmarkRegexPhone(b *testing.B) {
for i := 0; i < b.N; i++ {
regex("+1(555) 555-5555", "\\+\\d\\(\\d+\\) \\d+-\\d+")
}
}

func TestContains(t *testing.T) {
cases := []testCase{
testCase{args: []interface{}{[]interface{}{"a", "b"}, "a"}, expected: true},
Expand Down
1 change: 1 addition & 0 deletions rule.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ var defaultComparators = map[string]Comparator{
"ncontains": notContains,
"oneof": oneOf,
"noneof": noneOf,
"regex": regex,
}

// Rule is a our smallest unit of measure, each rule will be
Expand Down

0 comments on commit e7231e7

Please sign in to comment.