Go中正则匹配推荐先用regexp.Compile编译再复用MatchString,适合多次匹配;单次可用regexp.MatchString但有性能开销;注意RE2限制、转义规则及锚点使用。

在 Go 中使用 regexp 包做正则匹配,核心是先用 regexp.Compile 编译正则表达式,再调用 MatchString 判断字符串是否匹配。编译一次可复用,性能更好;若只用一次,也可用 regexp.MatchString(内部自动编译)。
使用 regexp.Compile + MatchString(推荐用于多次匹配)
适用于需对多个字符串重复匹配同一模式的场景,比如校验一批邮箱、提取日志中的 IP 地址等。编译后的 *regexp.Regexp 对象可安全并发使用。
- 调用
regexp.Compile返回正则对象和错误,必须检查错误(空字符串或非法语法会 panic 或返回 error) -
MatchString接收字符串,返回bool表示是否匹配(注意:是“是否包含该模式”,不是“是否完全等于”) - 若需完全匹配整串,正则两端加
^和$
示例:
package mainimport (
"fmt"
"regexp"
)
func main() {
re, err := regexp.Compile(`\d{3}-\d{2}-\d{4}`) // 匹配社保号格式
if err != nil {
panic(err)
}
fmt.Println(re.MatchString("123-45-6789")) // true
fmt.Println(re.MatchString("abc-12-3456")) // false
}
使用 regexp.MatchString(适合单次简单匹配)
底层自动调用 Compile 再匹配,简洁但每次调用都重新编译,高频使用时有性能开销。适合脚本、一次性校验等轻量场景。
立即学习“go语言免费学习笔记(深入)”;
- 第一个参数是正则字符串,第二个是待匹配文本
- 同样返回
bool和error,错误通常来自正则语法错误 - 无需手动管理正则对象,代码更短
示例:
matched, err := regexp.MatchString(`[a-z]+@[a-z]+\.[a-z]+`, "user@example.com")if err != nil {
log.Fatal(err)
}
fmt.Println(matched) // true
常见注意事项
Go 的正则引擎基于 RE2,不支持后向断言、非贪婪修饰符(如 .*?)等高级特性,但足够安全且高效。
- 反斜杠在 Go 字符串中需写双反斜杠:
\\d表示一个\d,或用原生字符串`\d` -
MatchString是子串匹配 ——re.MatchString("hello world", "ello")返回true - 要全匹配,请显式加锚点:
^\\d{3}-\\d{2}-\\d{4}$ - 编译失败(如
regxp.Compile("["))会返回 error,不可忽略
扩展:获取匹配内容(不止判断真假)
如果需要提取匹配结果,而不是只判断是否匹配,可用 FindString、FindStringSubmatch 或 FindStringSubmatchIndex 等方法。
-
re.FindString("abc123def")→"123" -
re.FindAllString("a1 b22 c333", -1)→[]string{"1", "22", "333"} -
re.ReplaceAllString("price: $100", "¥$1")→"price: ¥100"
这些方法都基于已编译的 *regexp.Regexp,所以仍建议优先 Compile 复用。










