Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Bug found in Golang Regexp ReplaceAllString?

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’)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading