Golang中regexp包支持RE2语法,用于正则匹配、查找和替换。首先导入"regexp"包,使用regexp.Compile()或MustCompile()编译正则表达式以提高复用性。常用方法包括MatchString判断匹配,FindString获取首个匹配,FindAllString获取所有匹配,FindStringSubmatch提取分组内容,ReplaceAllString进行替换。实际应用如验证邮箱格式^\[a-zA-Z0-9.\_%+-\]+@\[a-zA-Z0-9.-\]+\\.\[a-zA-Z\]{2,}$,或从URL/user/(\\d+)中提取用户ID。建议提前编译正则以提升性能。

在Golang中使用regexp包可以方便地进行正则表达式的匹配、查找和替换。Go标准库中的 regexp 包提供了对RE2语法的支持(不支持后向引用等复杂特性),性能良好且安全。
1. 导入 regexp 包
要使用正则功能,先导入 "regexp" 包:
import (
"fmt"
"regexp"
)
2. 编译正则表达式
推荐使用 regexp.Compile() 编译正则表达式,它会返回一个 *regexp.Regexp 对象或错误。编译后的正则可重复使用,提高效率。
if err != nil {
fmt.Println("正则格式错误:", err)
return
}
你也可以使用 regexp.MustCompile(),它在正则非法时会 panic,适合用于已知正确的硬编码正则:
立即学习“go语言免费学习笔记(深入)”;
3. 常用匹配方法
*regexp.Regexp 提供了多个实用方法:
fmt.Println(matched) // true FindString:返回第一个匹配的字符串 result := re.FindString("abc123def456")
fmt.Println(result) // 123 FindAllString:返回所有匹配项(切片) results := re.FindAllString("abc123def456", -1)
fmt.Println(results) // [123 456]
第二个参数控制返回数量:-1 表示全部,2 表示最多两个。
matches := re.FindStringSubmatch("日期: 2024-04-05")
if len(matches) > 0 {
fmt.Println("年:", matches[1]) // 2024
fmt.Println("月:", matches[2]) // 04
fmt.Println("日:", matches[3]) // 05
} ReplaceAllString:替换匹配内容 re := regexp.MustCompile(`\s+`)
text := "a b c"
result := re.ReplaceAllString(text, " ")
fmt.Println(result) // "a b c"
4. 实际应用场景示例
验证邮箱格式:
emailRegex := regexp.MustCompile(`^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`)fmt.Println(emailRegex.MatchString("test@example.com")) // true
提取URL中的ID:
url := "https://example.com/user/12345"re := regexp.MustCompile(`/user/(\d+)`)
matches := re.FindStringSubmatch(url)
if len(matches) > 1 {
fmt.Println("用户ID:", matches[1]) // 12345
} 基本上就这些。掌握
Compile、Find 系列和 Replace 方法,就能应对大多数文本处理需求。注意正则尽量提前编译,避免重复开销。










