Reputation: 109
Please help, I'm new with Go. I wrote function passing a string a regex and return boolan. my test keeps failing when validating correct format of Date of birth.
My test:
func TestIsMatchingRegex(t *testing.T) {
t.Parallel()
var tests = []struct {
dob string
reg string
expected bool
desc string
}{
{dob: "1928-06-05", reg: `[12][0-9]{3}-[01][0-9]-[0-3][0-9]`, expected: true, desc: "test1"},
{dob: "1928/06/05", reg: `[12][0-9]{3}-[01][0-9]-[0-3][0-9]`, expected: false, desc: "test2"},
}
for _, test := range tests {
actual := IsMatchingRegex(test.dob, test.reg)
assert.Equal(t, actual, test.expected, test.desc)
}
}
Matching function boolean
func IsMatchingRegex(s string, regex string) bool {
validFormat := regexp.MustCompile(regex)
matched := validFormat.MatchString(s)
if validFormat {
return false
}
return true
}
Upvotes: 1
Views: 8666
Reputation: 109318
Your test isn't failing, it can't compile because validFormat
is a Regexp
not a bool
.
Your bool is matched
, but you could simply return the result of MatchString
(or not use a separate function at all since it's a single line)
func IsMatchingRegex(s string, regex string) bool {
return regexp.MustCompile(regex).MatchString(s)
}
Upvotes: 3