Go语言中的正则表达式示例
正则表达式(regex)是一种基于模式搜索、提取和替换文本的强大工具。在Go语言(Golang)中,通过标准库regexp包实现正则表达式的使用。本文将深入探讨如何在Go中使用正则表达式:从简单的搜索到带捕获组的复杂替换。
1. regexp包基础
regexp包提供了两种主要方式:快速一次性使用(包级函数)和基于预编译模式的高性能操作(Regexp结构体)。对于重复使用,请始终提前编译模式。
编译正则表达式
package main
import ( "fmt" "regexp")
func main() { // 编译模式(推荐带错误处理的方法) pattern, err := regexp.Compile(`\\d+`) if err != nil { fmt.Println("编译错误:", err) return } // 简单情况——不带错误处理(无效模式会触发panic) patternMust := regexp.MustCompile(`[a-z]+`) fmt.Println(pattern, patternMust)}如果模式无效,Compile会返回错误。MustCompile会触发panic——仅用于静态模式。
2. 基本操作:搜索与匹配
让我们看看检查匹配和搜索子串的主要方法。
检查部分匹配
pattern := regexp.MustCompile(`go`)text := "我正在学习Golang"
// MatchString——字符串是否包含匹配模式的子串matched := pattern.MatchString(text)fmt.Println(matched) // true(因为"Golang"中包含"go")检查完全匹配
// 要检查整个字符串是否匹配模式,使用锚点^和$fullPattern := regexp.MustCompile(`^[a-zA-Z]+$`)fmt.Println(fullPattern.MatchString("Hello")) // truefmt.Println(fullPattern.MatchString("Hello1")) // false查找第一个匹配
datePattern := regexp.MustCompile(`\\d{2}\\.\\d{2}\\.\\d{4}`)text := "今天是2024年03月15日,明天是2024年03月16日"
// FindString——返回第一个匹配firstDate := datePattern.FindString(text)fmt.Println(firstDate) // "15.03.2024"查找所有匹配
// FindAllString——返回所有匹配的切片allDates := datePattern.FindAllString(text, -1) // -1表示所有匹配fmt.Println(allDates) // ["15.03.2024" "16.03.2024"]
// 限制数量:FindAllString(text, 1)——仅返回第一个3. 捕获组与替换
捕获组允许提取匹配的部分。在Go中,组用圆括号()表示。
按组提取数据
// 提取姓名和年龄的模式:"Name: [name], Age: [number]"personPattern := regexp.MustCompile(`Name: (\\w+), Age: (\\d+)`)text := "Name: Alexey, Age: 30"
// FindStringSubmatch——返回切片:[完整匹配, 组1, 组2, ...]matches := personPattern.FindStringSubmatch(text)if len(matches) > 0 { fmt.Println("完整匹配:", matches[0]) // "Name: Alexey, Age: 30" fmt.Println("姓名:", matches[1]) // "Alexey" fmt.Println("年龄:", matches[2]) // "30"}命名组(Go 1.21+)
// 从Go 1.21版本开始,可以使用命名组:(?P<name>pattern)pattern := regexp.MustCompile(`(?P<name>\\w+)@(?P<domain>\\w+\\.\\w+)`)text := "test@example.com"
// SubexpNames——获取组名称groupNames := pattern.SubexpNames()matches := pattern.FindStringSubmatch(text)
// 创建映射:组名称