Added match() regex matching to expr
This commit is contained in:
parent
02b3e83320
commit
767f86f01a
@ -43,6 +43,11 @@ func Test_header(t *testing.T) {
|
||||
headers: map[string][]string{"Foo": {"bar"}},
|
||||
err: "could not validate headers: failed to select 'Foo1' on *expr.Vars: no such key 'Foo1'",
|
||||
},
|
||||
{
|
||||
name: "regex matching key",
|
||||
expr: `{"expr":"match(Foo, \"^b\\\\wr\\\\s.*$\")"}`,
|
||||
headers: map[string][]string{"Foo": {"bar "}},
|
||||
},
|
||||
// {
|
||||
// name: "matching header with hyphen - TODO",
|
||||
// expr: `{"expr":"Content-type == \"application/json\""}`,
|
||||
|
||||
@ -3,11 +3,12 @@ package expr
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/spf13/cast"
|
||||
"reflect"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cast"
|
||||
|
||||
"github.com/PaesslerAG/gval"
|
||||
valid "github.com/asaskevich/govalidator"
|
||||
)
|
||||
@ -37,6 +38,7 @@ func StringFunctions() []gval.Language {
|
||||
gvalFunc("shorten", shorten),
|
||||
gval.Function("camelize", camelize),
|
||||
gval.Function("snakify", snakify),
|
||||
gval.Function("match", match),
|
||||
}
|
||||
}
|
||||
|
||||
@ -198,3 +200,21 @@ func camelize(s string) string {
|
||||
func snakify(s string) string {
|
||||
return strings.ToLower(strings.Replace(strings.Title(s), " ", "_", -1))
|
||||
}
|
||||
|
||||
func match(s string, regex interface{}) (b bool, err error) {
|
||||
var (
|
||||
r *regexp.Regexp
|
||||
)
|
||||
|
||||
switch v := regex.(type) {
|
||||
case *regexp.Regexp:
|
||||
r = v
|
||||
case string:
|
||||
if r, err = regexp.Compile(v); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
b = r.MatchString(s)
|
||||
return
|
||||
}
|
||||
|
||||
@ -189,3 +189,10 @@ func Example_substring_endOverflow() {
|
||||
// output:
|
||||
// o bar baz_test
|
||||
}
|
||||
|
||||
func Example_match() {
|
||||
eval(`match("foo bar baz_test", "^foo\\s.*$")`, nil)
|
||||
|
||||
// output:
|
||||
// true
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user