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

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>

此问题已经存在 在这里有答案: p>

  • 使用Golang替换的正则表达式 1个答案 span> li> ul> div>

    我想使用正则表达式组替换 golang code>中的字符串,就像在 python code>: p>

      re.sub(r“(\ d。*?)[az] +(\ d。*?)”,r“  \ 1 \ 2“,” 123abc123“)#python代码
      code>  pre> 
     
     

    那我该如何在golang中实现呢? p> div>

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.