别用FindStringSubmatch取捕获组,它只返回完整匹配项;取子组须用FindSubmatch或FindStringSubmatchIndex配合手动切片,且必须判空防panic。

直接说结论:别用 FindStringSubmatch 想当然取捕获组,它返回的是 [][]byte,下标越界或 nil 访问必 panic;要取子组,必须用 FindSubmatch 或 FindStringSubmatchIndex 配合手动切片。
regexp.Compile 失败后直接调用方法会 panic
Go 的 regexp.Compile 返回 (*Regexp, error),如果忽略 err 且编译失败,re 是 nil,后续任何方法调用(如 re.FindString)都会触发空指针 panic。
- 常见错误现象:
panic: runtime error: invalid memory address or nil pointer dereference - 典型错误写法:
re, _ := regexp.Compile(`(\d{3}-\d{2}`) // 少了个右括号,但没检查 err - 正确做法永远是:
if err != nil { return err }或log.Fatal(err),不能靠_吞掉错误 - 动态 pattern(比如来自 HTTP query、配置文件)绝不能用
regexp.MustCompile,它失败时只 panic,不带原始字符串,无法定位哪段正则写错了
取捕获组时 FindStringSubmatch 和 FindSubmatch 返回值不同
FindStringSubmatch 名字有误导性——它返回 [][]byte,但**只含完整匹配项,不含捕获组**。真正能取到 () 内容的,是 FindSubmatch(输入 []byte)或 FindStringSubmatchIndex(返回起始/结束位置)。
-
re.FindStringSubmatch([]byte("id=123&name=foo"))→ 返回[][]byte{[]byte("id=123&name=foo")},只有 1 个元素 -
re.FindSubmatch([]byte("id=123&name=foo"))→ 返回[][]byte{[]byte("id=123&name=foo"), []byte("123"), []byte("foo")},result[1]是第一个捕获组 - 务必先判空:
if len(submatches) > 2 { id := string(submatches[1]) },否则submatches[1]直接 panic - 命名捕获组(
(?P<id>\d+))在|拼接的复合正则中会导致SubexpNames()错位,建议拆成多个独立正则
替换时 ReplaceAllString 不解析 $1
ReplaceAllString 默认把替换字符串当字面量处理, 就是两个字符,不会被替换成第一个捕获组内容。想用占位符,必须换函数。
立即学习“go语言免费学习笔记(深入)”;
- 错误写法:
re.ReplaceAllString("a123b", "$1")→ 输出"$1",不是"123" - 正确方式一:
re.ReplaceAllStringSubmatch(src, []byte("$1")),注意第二个参数是[]byte,且需配合Expand或使用模板字符串 - 更可控的方式二:
re.ReplaceAllStringFunc(s, func(m string) string { sub := re.FindStringSubmatch([]byte(m)); return string(sub[1]) }) -
ReplaceAllLiteralString适合完全字面替换,比如把用户输入的关键词高亮,但不想触发任何正则语义
匹配中文、emoji 或换行符时 . 和 \w 失效
Go 的 regexp 基于 RE2,. 默认不匹配 \n,\w 等价于 [0-9A-Za-z_],对汉字、emoji 完全无效。
- 匹配中文:用
\p{Han},不是[一-龯](后者漏字、编码依赖强) - 匹配 emoji:用
\p{Extended_Pictographic},不是.或[\u{1F600}-\u{1F64F}](后者覆盖不全) - 让
.匹配换行符:在 pattern 开头加(?s),例如(?s)start.*end - 多行模式
(?m)只影响^和$,和.无关
最常被忽略的一点:所有 Find* 系列函数在无匹配时返回 nil 或空切片,但 nil 切片做 len() 安全,下标访问不安全;而 FindStringSubmatch 这类函数返回的是 [][]byte,长度为 0 时直接 result[0] 就 panic —— 这个边界比想象中更脆。


















