Go语言标准库中的regexp包提供了完整的正则表达式功能。主要函数包括:
regexp.Compile() - 编译正则表达式regexp.MustCompile() - 编译正则表达式(失败会panic)Regexp.MatchString() - 字符串匹配Regexp.FindString() - 查找匹配字符串标准的邮箱正则表达式应该包含以下验证规则:
^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$
这个正则表达式可以匹配:
完整实现代码示例:
package main
import (
"fmt"
"regexp"
)
func validateEmail(email string) bool {
pattern := `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`
re := regexp.MustCompile(pattern)
return re.MatchString(email)
}
func main() {
emails := []string{
"test@example.com",
"invalid.email",
"another.test@sub.domain.com",
}
for _, email := range emails {
fmt.Printf("%s: %v\n", email, validateEmail(email))
}
}
1. 预编译正则表达式提高性能:
var emailRegex = regexp.MustCompile(`^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`)
2. 更严格的域名验证:
^[a-zA-Z0-9._%+-]+@(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}$
Q: Go语言正则表达式性能如何?
A: Go的正则表达式实现经过优化,性能较好,但复杂表达式仍可能影响性能。
Q: 如何验证国际化邮箱?
A: 可以使用支持Unicode的正则表达式:^[\p{L}0-9._%+-]+@[\p{L}0-9.-]+\.[\p{L}]{2,}$