go - Regex Replace within Sub Match -
given string (a line in log file):
date=2017-06-29 03:10:01.140 -700 pdt,clientdatarate="12.0,18.0,24.0,36.0,48.0,54.0",host=superawesomehost.foo,foo=bar
i'd replace commas single space, within double quotes.
desired result:
date=2017-06-29 03:10:01.140 -700 pdt,clientdatarate="12.0 18.0 24.0 36.0 48.0 54.0",host=superawesomehost.foo,foo=bar
i've begun basic combination of regex , replaceallstring rapidly realizing don't understand how implement match group (?) needed accomplish this.
package main import ( "fmt" "log" "regexp" ) func main() { logline := "date=2017-06-29 03:10:01.140 -700 pdt,clientdatarate=\"12.0,18.0,24.0,36.0,48.0,54.0\",host=superawesomehost.foo,foo=bar" fmt.println("logline: ", logline) reg, err := regexp.compile("[^a-za-z0-9=\"-:]+") if err != nil { log.fatal(err) } repairedlogline := reg.replaceallstring(logline, ",") fmt.println("repairedlogline:", repairedlogline ) }
all appreciated.
you'll want use regexp.replaceallstringfunc
, allows use function result replacement of substring:
package main import ( "fmt" "log" "regexp" "strings" ) func main() { logline := `date=2017-06-29 03:10:01.140 -700 pdt,clientdatarate="12.0,18.0,24.0,36.0,48.0,54.0",host=superawesomehost.foo,foo=bar` fmt.println("logline: ", logline) reg, err := regexp.compile(`"([^"]*)"`) if err != nil { log.fatal(err) } repairedlogline := reg.replaceallstringfunc(logline, func(entry string) string { return strings.replace(entry, ",", " ", -1) }) fmt.println("repairedlogline:", repairedlogline) }
Comments
Post a Comment