gpt4 book ai didi

go - Go 中的 bool 函数

转载 作者:数据小太阳 更新时间:2023-10-29 03:35:25 25 4
gpt4 key购买 nike

请帮忙,我是 Go 的新手。我编写了函数,将字符串传递给正则表达式并返回 bool 值。在验证正确的出生日期格式时,我的测试一直失败。

我的测试:

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

}

匹配函数 bool 值

func IsMatchingRegex(s string, regex string) bool {
validFormat := regexp.MustCompile(regex)
matched := validFormat.MatchString(s)
if validFormat {
return false
}

return true
}

最佳答案

您的测试没有失败,它无法编译,因为 validFormatRegexp 而不是 bool

您的 bool 是匹配的,但您可以简单地返回 MatchString 的结果(或者根本不使用单独的函数,因为它是一行)

func IsMatchingRegex(s string, regex string) bool {
return regexp.MustCompile(regex).MatchString(s)
}

关于go - Go 中的 bool 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41551361/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com