日行一go:正则表达式

go 的正则表达式使用与动态语言PHP不同,需要先编译下正则表达式,才能进行下一步匹配,比如我要配置是否是有效的电子邮件地址,需要这么写:

func main() {
    emailAddrExp := regexp.MustCompile("^[a-zA-Z0-9][-a-zA-Z0-9-_]*@[-a-zA-Z0-9-_]+\\.[-a-zA-Z0-9-_]+$")

    cases := []string{
        "[email protected]",
        "invalid@",
        "时间,你好",
        "[email protected]",
    }

    for _, email := range cases {
        fmt.Println(email, emailAddrExp.MatchString(email))
    }
}

输出:

[email protected] true
invalid@ false
时间,你好 false
[email protected] true

Process finished with the exit code 0

Leave a Comment

Your email address will not be published. Required fields are marked *

PHP 8.1.1 - 16.019 ms, 0 Q