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

How to replace occured strings with a counter in Go regexp?

比如这句话,

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.

如何用

替换“让自由

[1]让自由, 《[2]让自由2》等

我搜索了 Go regexp 包,没有找到任何相关的增加计数器。 (只找到ReplaceAllStringFunc,不知道怎么用。)

您需要以某种方式在函数的连续调用之间共享计数器。一种方法是构造闭包。你可以这样做:

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

你需要这样的东西

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

确保你已经导入了所需的包。上面的工作是使用 Let freedom 作为正则表达式,然后使用一些条件来 return 预期的内容。