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

标签 regex dictionary go

我希望使用正则表达式将以下字符串解析为 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/

相关文章:

python - Python 列表在哪里保存它的值?

node.js - 如何在 Windows 上使用文件描述符 4(或其等价物)?

unit-testing - 在 go api 调用中测试

go - Revel Framework - Go Lang - 无法找到 Controller

android - 用户输入验证仅包含字母字符

java - 使用 Notepad++ 清理文本

python - 从字典中调用方法?

Java 正则表达式匹配不可打印的字符,除了\n\r 和\t

javascript - 当段落以引号结尾时,使用 Javascript 将段落拆分成句子

python - 在列表字典上使用 TfidfVectorizer