应优先使用 regexp.Compile 进行错误处理,仅对硬编码的可控正则用 MustCompile;提取多组捕获需用 FindSubmatch/FindSubmatchIndex;替换时用 ReplaceAllStringSubmatch 支持 $1 占位符;高频场景须预编译并复用 Regexp 实例。
如何用 regexp.MustCompile 安全地编译正则表达式
Go 中正则匹配必须先编译,regexp.MustCompile 是最常用方式,但它会在编译失败时直接 panic。线上服务里不能让一个非法正则搞垮整个程序。
实际开发中应优先考虑 regexp.Compile,它返回 (*Regexp, error),允许你做错误处理:
re, err := regexp.Compile(`\d{3}-\d{2}-\d{4}`) // 社保号格式
if err != nil {
log.Printf("正则编译失败: %v", err)
return
}
- 只有确定正则字面量完全可控(如硬编码的固定模式)才用
MustCompile - 用户输入、配置文件读取、环境变量注入的 pattern 必须走
Compile -
MustCompile的 panic 信息不带原始字符串,调试困难;而Compile的 error 会包含具体哪部分语法错
提取子匹配组要用 FindStringSubmatch 还是 FindStringSubmatchIndex
想从 “id=123&name=foo” 中取 123 和 foo,别直接用 FindAllString ——它只返回完整匹配,不拆组。
推荐组合:FindStringSubmatch 返回切片,直观;FindStringSubmatchIndex 返回位置索引,省内存且适合大文本: