doukan5332 2017-04-24 10:48
浏览 572
已采纳

Golang如何用正则表达式组替换字符串? [重复]

This question already has an answer here:

I want to use regex group to replace string in golang, just like as follow in python:

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

So how do I implement this in golang?

</div>
  • 写回答

1条回答 默认 最新

  • dseve40868 2017-04-24 10:50
    关注

    Use $1, $2, etc in replacement. For example:

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

    Playground: https://play.golang.org/p/ZHoz-X1scf.

    Docs: https://golang.org/pkg/regexp/#Regexp.ReplaceAllString.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?