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

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

Replace regular expression matches with values of a slice

问题

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

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中是否有实现这一功能的方法?我对golang非常陌生,所以对它的功能还不太了解。

英文:

My goal is to replace matches of a regular expression in a string. My code:

func ReplaceBase64ToDecodedImage(data string) string {
imageSrc := make(chan []string)
go base64toPng(content, imageSrc)
result := &lt;-imageSrc

fmt.Println(&quot;received string: &quot;, result)
re := regexp.MustCompile(`data:image/png;base64,[^]+[&quot;&#39;]([^&quot;&#39;]+)[&quot;&#39;]`)

s := re.ReplaceAllString(data, &quot;slice replacement values&quot;)

return s
}

I'm streaming slice of strings via channel to replacement function. In Javascript this can be done easily using shift() function:

const paragraph = &#39;This ??? is ??? and ???. Have you seen the ????&#39;;
const regex = /(\?\?\?)/g;
const replacements = [&#39;cat&#39;, &#39;cool&#39;, &#39;happy&#39;, &#39;dog&#39;];
const found = paragraph.replace(regex, () =&gt; replacements.shift());

console.log(found);

but I haven't found analog for this in go and ReplaceAllString() doesn't accept slices of strings. Is there a way to achieve this in golang? I'm very new to golang, so don't know much about it's capabilities yet.

答案1

得分: 0

你可以使用*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)
英文:

You can use ReplaceAllStringFunc function available on *regexp.Regexp. To achieve the similar functionality you did in JavaScript like this:

input := &quot;This ??? is ??? and ???. Have you seen the ????&quot;
replacements := []string{&quot;cat&quot;, &quot;cl&quot;, &quot;happyjaxvin&quot;, &quot;dog&quot;}
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

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

这段代码会将"???"替换为切片中的对应值,输出结果为:"This cat is cool and happy. Have you seen the dog?"

英文:

You can do this via the ReplaceAllStringFunc method. Using this we can create a method that will iterate through the slice and return each value:

<pre><code>
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)
}
</code></pre>

huangapple
  • 本文由 发表于 2022年4月13日 23:25:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/71860034.html
匿名

发表评论

匿名网友

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

确定