3
0

Added match() regex matching to expr

This commit is contained in:
Peter Grlica
2021-08-16 11:55:51 +02:00
parent 02b3e83320
commit 767f86f01a
3 changed files with 33 additions and 1 deletions

View File

@@ -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
}

View File

@@ -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
}