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

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

Replace regular expression matches with values of a slice

问题

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

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

我通过通道将字符串切片流式传输到替换函数中。在JavaScript中,可以使用shift()函数轻松实现这一点:

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

但是我在Go中没有找到类似的方法,而且ReplaceAllString()函数不接受字符串切片。在golang中是否有实现这一功能的方法?我对golang非常陌生,所以对它的功能还不太了解。

英文:

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

  1. func ReplaceBase64ToDecodedImage(data string) string {
  2. imageSrc := make(chan []string)
  3. go base64toPng(content, imageSrc)
  4. result := &lt;-imageSrc
  5. fmt.Println(&quot;received string: &quot;, result)
  6. re := regexp.MustCompile(`data:image/png;base64,[^]+[&quot;&#39;]([^&quot;&#39;]+)[&quot;&#39;]`)
  7. s := re.ReplaceAllString(data, &quot;slice replacement values&quot;)
  8. return s
  9. }

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

  1. const paragraph = &#39;This ??? is ??? and ???. Have you seen the ????&#39;;
  2. const regex = /(\?\?\?)/g;
  3. const replacements = [&#39;cat&#39;, &#39;cool&#39;, &#39;happy&#39;, &#39;dog&#39;];
  4. const found = paragraph.replace(regex, () =&gt; replacements.shift());
  5. 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中的功能,可以这样做:

  1. input := "This ??? is ??? and ???. Have you seen the ????"
  2. replacements := []string{"cat", "cl", "happyjaxvin", "dog"}
  3. r, _ := regexp.Compile(`\?\?\?`)
  4. res := r.ReplaceAllStringFunc(input, func(_ string) string {
  5. var repl string
  6. repl, replacements = replacements[0], replacements[1:]
  7. return repl
  8. })
  9. fmt.Println(res)
英文:

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

  1. input := &quot;This ??? is ??? and ???. Have you seen the ????&quot;
  2. replacements := []string{&quot;cat&quot;, &quot;cl&quot;, &quot;happyjaxvin&quot;, &quot;dog&quot;}
  3. r, _ := regexp.Compile(`\?\?\?`)
  4. res := r.ReplaceAllStringFunc(input, func(_ string) string {
  5. var repl string
  6. repl, replacements = replacements[0], replacements[1:]
  7. return repl
  8. })
  9. fmt.Println(res)

答案2

得分: 0

你可以通过ReplaceAllStringFunc方法来实现。使用这个方法,我们可以创建一个函数,遍历切片并返回每个值:

  1. import (
  2. "fmt"
  3. "regexp"
  4. )
  5. func main() {
  6. paragraph := "This ??? is ??? and ???. Have you seen the ????"
  7. re := regexp.MustCompile(`(\?\?\?)`)
  8. replacements := []string{"cat", "cool", "happy", "dog"}
  9. count := 0
  10. replace := func(string) string {
  11. count++
  12. return replacements[count-1]
  13. }
  14. s := re.ReplaceAllStringFunc(paragraph, replace)
  15. fmt.Println(s)
  16. }

这段代码会将"???"替换为切片中的对应值,输出结果为:"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:

确定