Advertisements
package main
import (
"fmt"
"regexp"
)
const sample = `darted`
func main() {
var re = regexp.MustCompile(`^(.*?)d(.*)$`)
s := re.ReplaceAllString(sample, `$1c$2`)
fmt.Println(s)//prints 'arted' expected: carted
}
Go playground: https://go.dev/play/p/-f0Cd_81eMX
Trying a non-alpha characters works (i.e. ‘$1.$2’ results in ‘.arted’)
Adding more than one alpha character works (i.e. ‘$1cl$2’ results in ‘clarted’)
Why doesn’t the above sample work?
Can someone show me what I’m doing wrong, or confirm this is a bug in Go that needs to be reported?
>Solution :
In your replacement:
`$1c$2`
This is as interpreted as a capture group literally named $1c
which doesn’t exist in the regex. You want ${1}c
.