Golang如何使用regexp匹配字符串_Golang regexp正则匹配方法总结

Go语言中regexp包基于RE2引擎提供正则支持,常用方法包括:1. 用regexp.Compile或MustCompile编译正则;2. MatchString判断匹配;3. FindString和FindAllString提取匹配内容;4. FindStringSubmatch获取分组结果;5. ReplaceAllString替换匹配项;6. 使用预定义字符类如\d、\w等。建议先编译后复用,确保高效安全处理字符串。

在 Go 语言中,regexp 包提供了对正则表达式的支持,可用于字符串的匹配、查找、替换等操作。它基于 RE2 引擎,不支持某些复杂的特性(如后向引用),但足够高效且安全。下面总结 Golang 中使用 regexp 进行字符串匹配的常用方法。

1. 编译正则表达式

Go 中推荐使用 regexp.Compile()regexp.MustCompile() 来创建一个 *Regexp 对象。前者返回错误信息,适合需要错误处理的场景;后者在编译失败时会 panic,适用于已知正则正确的场景。

示例:

re, err := regexp.Compile(`\d+`)
if err != nil {
    log.Fatal(err)
}
// 或者直接使用 MustCompile(确保正则合法)
re := regexp.MustCompile(`\d+`)

2. 判断是否匹配 MatchString

使用 MatchString() 方法判断字符串是否与正则匹配,返回布尔值。

示例:检查字符串是否包含数字

re := regexp.MustCompile(`\d+`)
matched := re.MatchString("hello123")
// 返回 true

3. 查找匹配内容 FindString / FindAllString

从字符串中提取匹配的内容:

  • FindString():返回第一个匹配的字符串。
  • FindAllString():返回所有匹配的字符串切片,第二个参数可限制返回数量(-1 表示全部)。

示例:

re := regexp.MustCompile(`\w+@\w+\.\w+`)
text := "联系我 at user@example.com 或 admin@test.org"

first := re.FindString(text)           // "user@example.com"
all := re.FindAllString(text, -1)      // ["user@example.com", "admin@test.org"]

4. 带分组的匹配 FindStringSubmatch

当正则中包含括号分组时,可以使用 FindStringSubmatch 获取主匹配和各子组。

示例:提取域名中的用户名和主机名

re := regexp.MustCompile(`(\w+)@(\w+\.\w+)`)
text := "email: john@gmail.com"

parts := re.FindStringSubmatch(text)
// parts[0] = "john@gmail.com"
// parts[1] = "john"
// parts[2] = "gmail.com"

若只需要子组,忽略完整匹配可用 parts[1:]

5. 替换匹配内容 ReplaceAllString

使用 ReplaceAllString() 将所有匹配替换为指定字符串,支持用 $1, $2 引用分组。

示例:隐藏邮箱用户名

re := regexp.MustCompile(`(\w+)@(\w+\.\w+)`)
result := re.ReplaceAllString("send to alice@example.com", "*@$2")
// 结果:"send to *@example.com"

6. 预定义字符类与常用模式

Go 正则支持常见的元字符:

  • \d:数字,等价于 [0-9]
  • \w:单词字符,[a-zA-Z0-9_]
  • \s:空白字符
  • ^ 和 $:行首与行尾
  • *+?:重复量词

示例:验证手机号(简单版)

re := regexp.MustCompile(`^1[3-9]\d{9}$`)
valid := re.MatchString("13812345678") // true

基本上就这些。Golang 的 regexp 虽然功能不如 Perl 或 Python 完整,但足以应对大多数文本处理需求,且性能稳定。关键是先编译再复用,避免重复解析正则表达式。掌握这几个核心方法,就能高效完成日常开发中的字符串匹配任务。不复杂但容易忽略细节,比如转义和分组索引,写的时候多测试即可。基本上就这些。