Go语言中regexp模块详细功能介绍与示例
Go语言的 regexp
模块提供了正则表达式操作,支持模式匹配、查找、替换和分割等功能。以下是核心方法及示例:
1. 编译正则表达式
regexp.Compile
编译正则表达式,返回 *Regexp
对象。如果正则非法,返回错误。
re, err := regexp.Compile(`\d+`)
if err != nil {
panic(err)
}
fmt.Println(re.MatchString("123")) // 输出: true
regexp.MustCompile
编译正则表达式,如果失败直接 panic(适用于全局变量初始化)。
re := regexp.MustCompile(`\d+`)
fmt.Println(re.MatchString("abc")) // 输出: false
2. 匹配检查
MatchString
直接检查字符串是否匹配正则表达式(无需编译)。
matched, _ := regexp.MatchString(`\d+`, "2023")
fmt.Println(matched) // 输出: true
Regexp.MatchString
使用预编译的正则对象检查匹配。
re := regexp.MustCompile(`^[A-Za-z]+$`)
fmt.Println(re.MatchString("Hello")) // 输出: true
3. 查找匹配
FindString
查找第一个匹配的字符串。
re := regexp.MustCompile(`\d+`)
fmt.Println(re.FindString("year 2023, month 12")) // 输出: 2023
FindAllString
查找所有匹配的字符串。
re := regexp.MustCompile(`\d+`)
matches := re.FindAllString("2023-12-31", -1)
fmt.Println(matches) // 输出: [2023 12 31]
FindStringIndex
返回第一个匹配的起始和结束索引。
re := regexp.MustCompile(`\d+`)
index := re.FindStringIndex("year 2023")
fmt.Println(index) // 输出: [5 9](匹配"2023")
4. 子匹配组(分组捕获)
FindStringSubmatch
查找第一个匹配及其子组。
re := regexp.MustCompile(`(\d{4})-(\d{2})-(\d{2})`)
match := re.FindStringSubmatch("2023-12-31")
fmt.Println(match) // 输出: [2023-12-31 2023 12 31]
FindAllStringSubmatch
查找所有匹配及其子组。
re := regexp.MustCompile(`(\d+)-(\d+)`)
matches := re.FindAllStringSubmatch("2023-12 1999-01", -1)
fmt.Println(matches)
// 输出: [[2023-12 2023 12] [1999-01 1999 01]]
5. 替换操作
ReplaceAllString
替换所有匹配项(支持 $1
引用子组)。
re := regexp.MustCompile(`(\d+)-(\d+)`)
result := re.ReplaceAllString("2023-12", "$2/$1")
fmt.Println(result) // 输出: 12/2023
ReplaceAllLiteralString
字面量替换(不解析 $1
)。
re := regexp.MustCompile(`\d+`)
result := re.ReplaceAllLiteralString("123", "X")
fmt.Println(result) // 输出: X
ReplaceAllFunc
通过函数动态生成替换内容。
re := regexp.MustCompile(`\d+`)
result := re.ReplaceAllStringFunc("123", func(s string) string {
return "[" + s + "]"
})
fmt.Println(result) // 输出: [123]
6. 分割字符串
Split
根据正则分割字符串。
re := regexp.MustCompile(`\s*,\s*`) // 匹配逗号及周围空格
parts := re.Split("a, b, c", -1)
fmt.Println(parts) // 输出: [a b c]
7. 扩展功能
Expand
动态生成替换内容(结合子组)。
re := regexp.MustCompile(`(\d+)-(\d+)`)
src := []byte("2023-12")
dst := []byte{}
template := []byte("Year: $1, Month: $2")
result := re.Expand(dst, template, src, re.FindSubmatchIndex(src))
fmt.Println(string(result)) // 输出: Year: 2023, Month: 12
8. 其他方法
QuoteMeta
转义正则中的特殊字符。
escaped := regexp.QuoteMeta(`.*+?^$()[]{}|`)
fmt.Println(escaped) // 输出: \.\*\+\?\^\$\(\)\[\]\{\}\|
Longest
启用最长匹配模式(默认贪婪模式)。
re := regexp.MustCompile(`a+?`).Longest() // 关闭贪婪模式
fmt.Println(re.FindString("aaaa")) // 输出: aaaa
总结
- 核心方法:
- 编译:
Compile
,MustCompile
- 匹配:
MatchString
,FindString
,FindAllString
- 替换:
ReplaceAllString
,ReplaceAllFunc
- 分割:
Split
- 子组:
FindStringSubmatch
,FindAllStringSubmatch
- 编译:
- 高级功能:
- 动态替换:
Expand
- 转义:
QuoteMeta
- 动态替换:
- 注意事项:
- 预编译正则表达式(
Compile
)提升性能。 *Regexp
对象是线程安全的,可在多个 goroutine 中使用。
- 预编译正则表达式(