如何在Go的正则表达式中用计数器替换出现的字符串?

huangapple go评论70阅读模式
英文:

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

问题

例如,在这个句子中,

让自由从纽约的崇山峻岭中回响。让自由从宾夕法尼亚州的高耸阿勒格尼山脉中回响。让自由从科罗拉多州的雪-capped洛基山脉中回响。让自由从加利福尼亚州的曲线斜坡中回响。

如何用"[1] 让自由","[2] 让自由2"等替换"让自由"。

我搜索了Go的regexp包,未能找到与增加计数器相关的内容。(只找到了ReplaceAllStringFunc,但我不知道如何使用它。)

英文:

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

答案1

得分: 2

你需要像这样的代码:

import (
    "fmt"
    "regexp"
)

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

确保已导入所需的包。上述代码通过使用Let freedom作为正则表达式,并使用一些条件来返回预期的结果。

英文:

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.

答案2

得分: 0

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

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

这段代码使用闭包来共享计数器。在每次调用repl函数时,计数器会递增,并将计数器的值与匹配的字符串一起返回。最终,str2将包含替换后的字符串。

英文:

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

huangapple
  • 本文由 发表于 2015年1月11日 20:46:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/27887206.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定