2 回答

TA貢獻1829條經(jīng)驗 獲得超7個贊
您可以通過 ReplaceAllStringFunc 方法執(zhí)行此操作。使用它我們可以創(chuàng)建一個方法來遍歷切片并返回每個值:
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條經(jīng)驗 獲得超4個贊
您可以使用ReplaceAllStringFunc上可用的功能*regexp.Regexp。要實現(xiàn)您在 JavaScript 中所做的類似功能,請執(zhí)行以下操作:
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 關(guān)注
- 146 瀏覽
添加回答
舉報