Replace the regex routine using the function

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.

+8
regex go
source share
1 answer

I don't like the code below, but it seems to do what you think is needed:

 package main import ( "fmt" "regexp" ) func main() { input := `bla bla b:foo="hop" blablabla b:bar="hu?"` r := regexp.MustCompile(`\bb:\w+="([^"]+)"`) r2 := regexp.MustCompile(`"([^"]+)"`) fmt.Println(r.ReplaceAllStringFunc(input, func(m string) string { return r2.ReplaceAllString(m, `"${2}whatever"`) })) } 

Playground


Exit

 bla bla b:foo="whatever" blablabla b:bar="whatever" 

EDIT: Take II.


 package main import ( "fmt" "regexp" ) func computedFrom(s string) string { return fmt.Sprintf("computedFrom(%s)", s) } func main() { input := `bla bla b:foo="hop" blablabla b:bar="hu?"` r := regexp.MustCompile(`\bb:\w+="([^"]+)"`) r2 := regexp.MustCompile(`"([^"]+)"`) fmt.Println(r.ReplaceAllStringFunc(input, func(m string) string { match := string(r2.Find([]byte(m))) return r2.ReplaceAllString(m, computedFrom(match)) })) } 

Playground


Output:

 bla bla b:foo=computedFrom("hop") blablabla b:bar=computedFrom("hu?") 
+1
source share

All Articles