2 回答
TA贡献1829条经验 获得超7个赞
您可以通过 ReplaceAllStringFunc 方法执行此操作。使用它我们可以创建一个方法来遍历切片并返回每个值:
import (
"fmt"
"regexp"
)
func main() {
paragraph := "This ??? is ??? and ???. Have you seen the ????"
re := regexp.MustCompile(`(\?\?\?)`)
replacements := []string{"cat", "cool", "happy", "dog"}
count := 0
replace := func(string) string {
count++
return replacements[count-1]
}
s := re.ReplaceAllStringFunc(paragraph, replace)
fmt.Println(s)
}
TA贡献1836条经验 获得超4个赞
您可以使用ReplaceAllStringFunc上可用的功能*regexp.Regexp。要实现您在 JavaScript 中所做的类似功能,请执行以下操作:
input := "This ??? is ??? and ???. Have you seen the ????"
replacements := []string{"cat", "cl", "happyjaxvin", "dog"}
r, _ := regexp.Compile(`\?\?\?`)
res := r.ReplaceAllStringFunc(input, func(_ string) string {
var repl string
repl, replacements = replacements[0], replacements[1:]
return repl
})
fmt.Println(res)
- 2 回答
- 0 关注
- 118 浏览
添加回答
举报