如何用Go regexp中的计数器替换出现的字符串?

For example, in this sentence,

Let freedom ring from the mighty mountains of New York. Let freedom ring from the heightening Alleghenies of Pennsylvania. Let freedom ring from the snow-capped Rockies of Colorado. Let freedom ring from the curvaceous slopes of California.

how to replace "Let freedom" with

"[1] Let freedom", "[2] Let freedom2", and so on.

I searched the Go regexp package, failed to find anything related increase counter. (Only find the ReplaceAllStringFunc, but I don't know how to use it.)

You need to somehow share counter between successive calls to your function. One way to do this is to construct closure. You can do it this way:

package main

import (
    "fmt"
    "regexp"
)

func main() {
    str := "Let freedom ring from the mighty mountains of New York. Let freedom ring from the heightening Alleghenies of Pennsylvania. Let freedom ring from the snow-capped Rockies of Colorado. Let freedom ring from the curvaceous slopes of California."
    counter := 1
    repl := func(match string) string {
        old := counter
        counter++
        if old != 1 {
            return fmt.Sprintf("[%d] %s%d", old, match, old)
        }
        return fmt.Sprintf("[%d] %s", old, match)
    }
    re := regexp.MustCompile("Let freedom")
    str2 := re.ReplaceAllStringFunc(str, repl)
    fmt.Println(str2)
}

You need something like this

r, i := regexp.MustCompile("Let freedom"), 0
r.ReplaceAllStringFunc(input, func(m string) string {
   i += 1
   if i == 1 {
     return "[1]" + m 
   }
   return fmt.Sprintf("[%d] %s%d", i, m, i)
})

Make sure you've imported required packages.. The above works by using Let freedom as the regex and then using some conditions to return what is intended.