将正则表达式匹配项替换为切片的值



我的目标是替换字符串中正则表达式的匹配项。我的代码:

func ReplaceBase64ToDecodedImage(data string) string {
imageSrc := make(chan []string)
go base64toPng(content, imageSrc)
result := <-imageSrc
fmt.Println("received string: ", result)
re := regexp.MustCompile(`data:image/png;base64,[^]+["']([^"']+)["']`)
s := re.ReplaceAllString(data, "slice replacement values")
return s
}

我正在通过通道将字符串片段流式传输到替换功能。在Javascript中,使用shift((函数可以很容易地做到这一点:

const paragraph = 'This ??? is ??? and ???. Have you seen the ????';
const regex = /(???)/g;
const replacements = ['cat', 'cool', 'happy', 'dog'];
const found = paragraph.replace(regex, () => replacements.shift());
console.log(found);

但我在go中没有找到类似的方法,ReplaceAllString((不接受字符串切片。在戈兰有办法做到这一点吗?我对golang很陌生,所以对它的功能还不太了解。

您可以通过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)
}

您可以使用*regexp.Regexp上可用的ReplaceAllStringFunc函数。为了实现您在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)

最新更新