Home > Software design >  Replace regular expression matches with values of a slice
Replace regular expression matches with values of a slice

Time:04-14

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 := <-imageSrc

fmt.Println("received string: ", result)
re := regexp.MustCompile(`data:image/png;base64,[^] ["']([^"'] )["']`)

s := re.ReplaceAllString(data, "slice replacement values")

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 = '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);

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.

CodePudding user response:

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:


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)
}

CodePudding user response:

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

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)
  • Related