Go中字符串正则替换主要用regexp包的ReplaceAllString、ReplaceAllStringFunc和ReplaceAllStringSubmatchFunc;需先编译正则,再调用对应方法,分别适用于静态替换、动态逻辑替换和捕获组引用场景。

在 Go 语言中,使用 regexp 包替换字符串主要靠 *Regexp.ReplaceAllString、*Regexp.ReplaceAllStringFunc 和更灵活的 *Regexp.ReplaceAllStringSubmatchFunc 等方法。核心是先编译正则表达式,再调用替换函数。
基础替换:ReplaceAllString
最常用的是 ReplaceAllString,它将所有匹配的子串替换成指定字符串:
- 第一个参数是原字符串,第二个是替换内容(不支持捕获组引用)
- 返回新字符串,原字符串不变(Go 字符串不可变)
把所有数字替换成 "[num]"
re := regexp.MustCompile(`\d+`)
result := re.ReplaceAllString("abc123def456", "[num]")
// result == "abc[num]def[num]"
带捕获组的替换:ReplaceAllStringFunc + 自定义逻辑
如果需要根据匹配内容动态生成替换值(比如转大写、加前缀),用 ReplaceAllStringFunc 更合适:
立即学习“go语言免费学习笔记(深入)”;
- 传入一个函数,参数是每次匹配到的完整字符串,返回替换后的字符串
- 适合简单逻辑,如大小写转换、条件判断
把每个单词首字母大写
re := regexp.MustCompile(`\b\w+`)
result := re.ReplaceAllStringFunc("hello world go", strings.Title)
// result == "Hello World Go"
高级替换:ReplaceAllStringSubmatchFunc(支持 $1 引用)
若需在替换字符串中引用捕获组(类似 JavaScript 的 $1、$2),Go 原生不直接支持,但可用 ReplaceAllStringSubmatchFunc 手动实现:
- 接收匹配的完整字符串,内部用
FindStringSubmatch提取分组 - 或更推荐:用
ReplaceAllStringSubmatch配合[][]byte处理(适合二进制安全场景)
re := regexp.MustCompile(`(\w+):(\d+)`)
text := "age:25, score:98"
result := re.ReplaceAllStringFunc(text, func(m string) string {
sub := re.FindStringSubmatch([]byte(m))
if len(sub) > 0 && len(sub[0]) > 1 {
// 提取第一个捕获组(注意:sub[0] 是全匹配,sub[1] 是第一个括号内容)
if len(sub) > 1 {
key := string(sub[1])
val := string(sub[2])
return key + "=" + val
}
}
return m
})
// result == "age=25, score=98"
注意事项与技巧
- 正则表达式尽量用
MustCompile(开发期报错明确)或Compile(运行期容错) - 避免在循环中反复
Compile,应提前编译并复用 *Regexp 实例 - 替换内容含特殊字符(如反斜杠、美元符)时注意转义,Go 字符串字面量本身需双反斜杠
- 如需全局替换且保留原始换行/Unicode,确保正则模式未误设
(?m)或(?s)等标志










