Search code examples
goregexp-replace

Golang regex replace behavior


I have a simple regex in Go and noticed an odd behavior when using the ReplaceAllString function.

package main

import (
    "fmt"
    "regexp"
)

func main() {
    var re = regexp.MustCompile("(.*)(b.*)")
    fmt.Println(re.ReplaceAllString("abc", "$1,d"))
    fmt.Println(re.ReplaceAllString("abc", "$1d"))
    fmt.Println(re.ReplaceAllString("abc", "$1d.f"))
    fmt.Println(re.ReplaceAllString("abc", "$1 d"))
}

https://play.golang.org/p/reb0T9Eadw3

I expected something like this

a,d
ad
ad.f
a d

But the actual result is

a,d

.f
a d

I tested the regex also over at https://regex101.com/r/sROI28/1 and saw that my token replace statement is the issue. But I do not fully understand the underlying issue.

Am I using the $ signs incorrectly? How would I have to adapt my replace-string to get to the expected/desired output?


Solution

  • The problem is the d after the 1. You should surround the group number with curly brackets:

    package main
    
    import (
        "fmt"
        "regexp"
    )
    
    func main() {
        var re = regexp.MustCompile("(.*)(b.*)")
        fmt.Println(re.ReplaceAllString("abc", "${1},d"))
        fmt.Println(re.ReplaceAllString("abc", "${1}d"))
        fmt.Println(re.ReplaceAllString("abc", "${1}d.f"))
        fmt.Println(re.ReplaceAllString("abc", "${1} d"))
    }
    

    Otherwise the group is extended to 1d which is not a valid group and returns an empty expression.