我希望使用正则表达式将以下字符串解析为 map[string]string
:
time="2017-05-30T19:02:08-05:00" level=info msg="some log message" app=sample size=10
我正在尝试创建一个 map
m["time"] = "2017-05-30T19:02:08-05:00"
m["level"] = "info"
等等
我已经尝试使用 regex.FindAllStringIndex
但不能完全想出一个合适的正则表达式?这是正确的方法吗?
最佳答案
这不是使用正则表达式,而只是一个如何使用 strings.FieldsFunc 实现相同目的的示例.
https://play.golang.org/p/rr6U8xTJZT
package main
import (
"fmt"
"strings"
"unicode"
)
const foo = `time="2017-05-30T19:02:08-05:00" level=info msg="some log message" app=sample size=10`
func main() {
lastQuote := rune(0)
f := func(c rune) bool {
switch {
case c == lastQuote:
lastQuote = rune(0)
return false
case lastQuote != rune(0):
return false
case unicode.In(c, unicode.Quotation_Mark):
lastQuote = c
return false
default:
return unicode.IsSpace(c)
}
}
// splitting string by space but considering quoted section
items := strings.FieldsFunc(foo, f)
// create and fill the map
m := make(map[string]string)
for _, item := range items {
x := strings.Split(item, "=")
m[x[0]] = x[1]
}
// print the map
for k, v := range m {
fmt.Printf("%s: %s\n", k, v)
}
}
关于regex - 用于将键值对解析为字符串映射的 Golang 正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44277222/