douping3860 2017-05-31 06:27
浏览 296
已采纳

Golang正则表达式,用于将键值对解析为字符串映射

I'm looking to parse the following string into a map[string]string using a regular expression:

time="2017-05-30T19:02:08-05:00" level=info msg="some log message" app=sample size=10

I'm trying to create a map that would have

m["time"] = "2017-05-30T19:02:08-05:00"
m["level"] = "info"

etc

I have tried using regex.FindAllStringIndex but can't quite come up with an appropriate regex? Is this the correct way to go?

  • 写回答

3条回答 默认 最新

  • duanguan1573 2017-05-31 10:21
    关注

    This is not using regex but is just an example of how to achieve the same by using 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
    ", k, v)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置