Say I have strings like
input := `bla bla b:foo="hop" blablabla b:bar="hu?"`
and I want to replace the parts between quotation marks in b:foo="hop" or b:bar="hu?" using function.
Itโs easy to build a regex to match and load like
r := regexp.MustCompile(`\bb:\w+="([^"]+)"`)
and then call ReplaceAllStringFunc , but the problem is that the callback gets the whole match, not the fake:
fmt.Println(r.ReplaceAllStringFunc(input, func(m string) string { // m is the whole match here. Damn. }))
How to replace the load?
Currently, I have not found a better solution than expanding myself m inside the callback with a regular expression and rebuilding the line after processing the send.
I would use an alternative approach with a positive outlook if they were available in Go, but it is not (and they should not be necessary in any case).
What can i do here?
EDIT: here is my current solution, which I would like to simplify:
func complexFunc(s string) string { return "dbvalue("+s+")" // this could be more complex } func main() { input := `bla bla b:foo="hop" blablabla b:bar="hu?"` r := regexp.MustCompile(`(\bb:\w+=")([^"]+)`) fmt.Println(r.ReplaceAllStringFunc(input, func(m string) string { parts := r.FindStringSubmatch(m) return parts[1] + complexFunc(parts[2]) })) }
(playground)
My concern is that I have to regex twice. It doesnโt sound like that.
regex go
Denys seguret
source share