doushou8730 2019-04-02 03:43
浏览 41
已采纳

golang regex键:值问题

I'm trying to split a syslog message into a key:value 'map[string]string', but cannot seem to get the regex right.

The source string delimits its keys and values by an '='. However, each pair is seperated by spaces with spaces actually being within the values. I have it pretty close but as you can see from the link below, I can't get the rest of the 'start', 'end', or 'suser' values.

Here's a link to a golang playground showing my exact problem:

package main

import (
    "fmt"
    "regexp"
)

var rex = regexp.MustCompile("(\\w+)=(.+?[^\\\\s\\\\w+=]+)")

func main() {
    conn := "start=Mar 26 2019 10:36:14 +00:00 end=Mar 26 2019 10:36:14 +00:00 suser=AD.COM\\\\Username src=10.1.0.51"
    data := rex.FindAllStringSubmatch(conn, -1)

    res := make(map[string]string)
    for _, kv := range data {
        k := kv[1]
        v := kv[2]
        res[k] = v
    }
    for v := range res {fmt.Printf("%s: %v
", v, res[v])}

}
  • 写回答

2条回答 默认 最新

  • duandou2763 2019-04-02 07:05
    关注

    You may use

     var rex = regexp.MustCompile(`(\w+)=([^=]*\w)(?:\s|$)`)
    

    See the Go demo, the regex demo online and the Regulex graph.

    enter image description here

    Regex details

    • (\w+) - Capturing group 1: one or more word chars
    • = - a = char
    • ([^=]*\w) - Capturing group 2: any 0+ chars other than = and then a word char
    • (?:\s|$) - either a whitespace or end of string.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 shape_predictor_68_face_landmarks.dat
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制