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 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛