Go中的布尔函数

huangapple go评论76阅读模式
英文:

Boolean functions in Go

问题

请帮忙,我刚开始学习Go语言。我编写了一个函数,传入一个字符串和一个正则表达式,并返回布尔值。但是当验证出生日期的正确格式时,我的测试一直失败。

我的测试代码如下:

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

匹配函数的布尔返回值如下:

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

    return false
}
英文:

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
}

答案1

得分: 2

你的测试没有失败,它无法编译,因为validFormat是一个Regexp而不是bool

你的boolmatched,但你可以简单地返回MatchString的结果(或者根本不使用单独的函数,因为它只有一行代码)。

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

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

huangapple
  • 本文由 发表于 2017年1月9日 23:30:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/41551361.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定