7

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?

ekad
  • 14,436
  • 26
  • 44
  • 46
roger
  • 9,063
  • 20
  • 72
  • 119

1 Answers1

22

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.

Ainar-G
  • 34,563
  • 13
  • 93
  • 119