Skip to content

Commit

Permalink
Add IsRegex and tests for it (#155)
Browse files Browse the repository at this point in the history
  • Loading branch information
kasraabdollahi committed Feb 6, 2021
1 parent 7a23bdc commit 4df403f
Show file tree
Hide file tree
Showing 2 changed files with 75 additions and 0 deletions.
7 changes: 7 additions & 0 deletions validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -819,6 +819,13 @@ func IsRsaPublicKey(str string, keylen int) bool {
return bitlen == int(keylen)
}

func IsRegex(str string) bool {
if _, err := regexp.Compile(str); err == nil {
return true
}
return false
}

func toJSONName(tag string) string {
if tag == "" {
return ""
Expand Down
68 changes: 68 additions & 0 deletions validator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3573,6 +3573,74 @@ bQIDAQAB
}
}

func TestIsRegex(t *testing.T) {
t.Parallel()

var tests = []struct {
param string
expected bool
}{
{"^$", true},
{"$^", true},
{"^^", true},
{"$$", true},
{"a+", true},
{"a++", false},
{"a*", true},
{"a**", false},
{"a+*", false},
{"a*+", false},
{"[a+]+", true},
{"\\w+", true},
{"\\y+", false},
{"[asdf][qwer]", true},
{"[asdf[", false},
{"[asdf[]", true},
{"[asdf[][]", false},
{"(group2)(group3)", true},
{"(invalid_paranthesis(asdf)", false},
{"a?", true},
{"a??", true},
{"a???", false},
{"a\\???", true},
{"asdf\\/", true},
{"asdf/", true},
{"\\x61", true},
{"\\xg1", false},
{"\\x6h", false},
{"[asdf[", false},
{"[A-z]+", true},
{"[z-A]+", false},
{"[a-z-A]", true},
{"a{3,6}", true},
{"a{6,3|3,6}", true},
{"a{6,3}", false},
{"a|b", true},
{"a|b|", true},
{"a|b||", true}, //But false in python RE
{"(?:)", true},
{"(?)", true}, //But false in python RE
{"?", false},
{"(?::?)", true},
{"(?:?)", false},
{"(()?)", true},
{"(?:?)", false},
{"(A conditional matching)? (?(1)matched|not matched)", false}, //But true in python RE
{"(A conditional matching)? (?(2)matched|not matched)", false},
{"(?:A conditional matching)? (?(1)matched|not matched)", false},
{"(?:[a-z]+)?", true},
{"(?#[a-z]+)?", false},
{"(?P<name>[a-z]+)", true},
{"(?P<name<>>[a-z]+)", false},
}
for _, test := range tests {
actual := IsRegex(test.param)
if actual != test.expected {
t.Errorf("Expected IsNumeric(%q) to be %v, got %v", test.param, test.expected, actual)
}
}
}

func TestIsIMSI(t *testing.T) {
tests := []struct {
param string
Expand Down

0 comments on commit 4df403f

Please sign in to comment.