正则表达式是处理字符串的强大工具,Go语言通过regexp包提供了完善的正则支持。
Go语言使用RE2语法标准,与Perl风格正则类似但略有不同:
// 简单匹配示例
pattern := `foo.?`
r := regexp.MustCompile(pattern)
matched := r.MatchString("seafood")
fmt.Println(matched) // true
. 匹配任意单个字符* 匹配前一个字符0次或多次+ 匹配前一个字符1次或多次? 匹配前一个字符0次或1次\d 匹配数字\w 匹配单词字符正则表达式应当预编译以提高性能:
var emailRegex = regexp.MustCompile(`^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`)
func validateEmail(email string) bool {
return emailRegex.MatchString(email)
}
使用括号进行分组捕获:
re := regexp.MustCompile(`(\w+)@(\w+\.\w+)`)
matches := re.FindStringSubmatch("user@example.com")
// matches[0] = "user@example.com"
// matches[1] = "user"
// matches[2] = "example.com"
使用正则进行字符串替换:
re := regexp.MustCompile(`(\d+)-(\d+)-(\d+)`)
result := re.ReplaceAllString("2023-05-15", "$2/$3/$1")
// 输出: 05/15/2023
chineseRegex := regexp.MustCompile(`[\p{Han}]`) // 匹配单个汉字
Go默认使用非贪婪匹配,要使用贪婪匹配可在量词后加?:
// 非贪婪匹配
re := regexp.MustCompile(`<.*?>`)
通过本文的学习,您应该已经掌握了Golang正则表达式的基本使用方法和优化技巧。正则表达式虽然强大,但也需要合理使用才能发挥最大价值。