我的日志格式如下:
Sep 22 12:46:39 10.9.0.203 hotspot,debug Hotspot_account: T-34:23:BA:75:C6:7E (10.40.0.135): some action
和:
Sep 22 12:46:39 10.9.0.203 hotspot,error,info,debug Hotspot_account: T-34:23:BA:75:C6:7E (10.40.0.135): some action: detailed info about action
我的正则表达式:
^.*[^\:]*\d\d\:\d\d\:\d\d[^\:]*?\s\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\s(?P<service>\w+),(?P<severity>\w+)(.+?):\s(?P<mac>\S+)\s.(?P<ip>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})(.+?) (?P<action>.+)[\(:,\-].(?P<message>[\w\s]+)
像我想要的那样捕获第二个,现在我需要将其修改为当操作后没有任何内容时将字段“消息”留空,以及当操作后是一些详细信息时将其放入字段“消息”中,就像它所做的那样现在。
这可能吗,或者我应该使用 2 个单独的正则表达式来处理两种类型的消息?
最佳答案
您可以在模式末尾添加一个替换,以匹配行尾(多行模式下为 $
)或消息。仅当您输入 (?P<action>.+)
时,此交替才有效。懒惰(即 (?P<action>.+?)
)。
这是更新的正则表达式:
^.*[^:]*\d\d\:\d\d\:\d\d[^:]*?\s\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\s(?P<service>\w+),(?P<severity>\w+)(.+?):\s(?P<mac>\S+)\s.(?P<ip>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})(.+?) (?P<action>.+?)(?:$|[(:,-].(?P<message>[\w\s]+))
参见demo (在演示中,我需要在开始时使用 ^.*[^:\n]
来进行演示)。
关于regex - 匹配或没有匹配项时留空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32715376/