【问题标题】:How golang replace string by regex group? [duplicate]golang如何用正则表达式组替换字符串? [复制]
【发布时间】:2017-09-21 00:24:32
【问题描述】:

我想用正则表达式组替换golang中的字符串,就像python中的如下:

re.sub(r"(\d.*?)[a-z]+(\d.*?)", r"\1 \2", "123abc123") # python code

那么如何在 golang 中实现呢?

【问题讨论】:

标签: regex go regex-group


【解决方案1】:

使用$1$2等代替。例如:

re := regexp.MustCompile(`(foo)`)
s := re.ReplaceAllString("foo", "$1$1")
fmt.Println(s)

游乐场:https://play.golang.org/p/ZHoz-X1scf

文档:https://golang.org/pkg/regexp/#Regexp.ReplaceAllString

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-07
    • 1970-01-01
    • 2018-07-13
    • 2015-11-30
    • 2021-11-29
    相关资源
    最近更新 更多