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 更合适:
立即学习“go语言免费学习笔记(深入)”;
把每个单词首字母大写
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) 等标志以上就是如何在Golang中使用regexp替换字符串_替换匹配的内容的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号