Go中字符串正则替换主要用regexp包的ReplaceAllString、ReplaceAllStringFunc和ReplaceAllStringSubmatchFunc;需先编译正则,再调用对应方法,分别适用于静态替换、动态逻辑替换和捕获组引用场景。
在 Go 语言中,使用 regexp 包替换字符串主要靠 *Regexp.ReplaceAllString、*Regexp.ReplaceAllStringFunc 和更灵活的 *Regexp.ReplaceAllStringSubmatchFunc 等方法。核心是先编译正则表达式,再调用替换函数。
最常用的是 ReplaceAllString,它将所有匹配的子串替换成指定字符串:
把所有数字替换成 "[num]"
re := regexp.MustCompile(`\d+`)
result := re.ReplaceAllString("abc123def456", "[num]")
// result == "abc[num]def[num]"
如果需要根据匹配内容动态生成替换值(比如转大写、加前缀),用 ReplaceAllStringFunc 更合适:
把每个单词首字母大写
re := regexp.MustCompile(`\b\w+`)
result := re.ReplaceAllStringFunc("hello world go", strings.Title)
// result == "Hello World Go"
若需在替换字符串中引用捕获组(类似 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 实例(?m) 或 (?s) 等标志