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