簡體   English   中英

Python 正則表達式 - 捕獲重復模式組

[英]Python Regex - Capturing Groups of Repeating Patterns

我有一個正在嘗試解析的日志文件。 日志文件示例如下:

10 月 23 日 13:03:03.714012 prod1_xyz(RSVV)[201]:#msgtype=EVENT #server=Web/Dev@server1web #func=LKZ_WriteData(第 2992 行)#rc=0 #msgid=XYZ0064 #reqid=0 #msg= Web 活動結束(第 200 節,# SysD 1,文件 222,字節 343422089928,錯誤 0,中止文件 0,忙碌文件 0)

我想提取所有以 hash 開頭的文本,並有一個鍵和值。 例如,#msgtype=EVENT。 任何僅具有 hash 且沒有“=”符號的文本都將被視為一個值。

所以在上面的日志條目中,我想要一個看起來像這樣的列表

#msgtype=EVENT
#server=Web/Dev@server1web
#func=LKZ_WriteData ( line 2992 ) 
#rc=0
#msgid=XYZ0064 
#reqid=0
#msg=Web Activity end (section 200, # SysD 1, Files 222, Bytes 343422089928, Errors 0, Aborted Files 0, Busy Files 0) (Notice the hash present in the middle of the text)

我已經嘗試過 Python 正則表達式 findall 選項,但我無法捕獲所有數據。

例如:

str='Oct 23 13:03:03.714012 prod1_xyz(RSVV)[201]: #msgtype=EVENT #server=Web/Dev@server1web #func=LKZ_WriteData ( line 2992 ) #rc=0 #msgid=XYZ0064 #reqid=0 #msg=Web Activity end (section 200, # SysD 1, Files 222, Bytes 343422089928, Errors 0, Aborted Files 0, Busy Files 0)'

z = re.findall("(#.+?=.+?)(:?#|$)",str)
print(z)

Output:

[('#msgtype=EVENT ', '#'), ('#func=LKZ_WriteData ( line 2992 ) ', '#'), ('#msgid=XYZ0064 ', '#'), ('#msg=Web Activity end (section 200, ', '#')]

(:?#|$)是一個捕獲組,它匹配一個可選的: ,然后是# ,或者字符串的結尾。 由於re.findall返回所有捕獲的子字符串,因此結果是一個元組列表。

你需要

re.findall(r'#[^\s=]+=.*?(?=\s*#[^\s=]+=|$)', text)

查看正則表達式演示

正則表達式詳細信息

  • #[^\s=]+ - #然后是除空格和=之外的任何 1+ 個字符
  • = - a =字符
  • .*? - 除換行符以外的任何 0+ 字符,盡可能少
  • (?=\s*#[^\s=]+=|$) - 最多(且不包括)0+ 個空格、 # 、1+ 個除空格和=之外的字符,然后=或字符串末尾。
import re

s = "Oct 23 13:03:03.714012 prod1_xyz(RSVV)[201]: #msgtype=EVENT #server=Web/Dev@server1web #func=LKZ_WriteData ( line 2992 ) #rc=0 #msgid=XYZ0064 #reqid=0 #msg=Web Activity end (section 200, # SysD 1, Files 222, Bytes 343422089928, Errors 0, Aborted Files 0, Busy Files 0)"

a = re.findall('#(?=[a-zA-Z]+=).+?=.*?(?= #[a-zA-Z]+=|$)', s)

result = [item.split('=') for item in a]

print(result)

給出:

[['#msgtype', 'EVENT'], ['#server', 'Web/Dev@server1web'], ['#func', 'LKZ_WriteData ( line 2992 )'], ['#rc', '0'], ['#msgid', 'XYZ0064'], ['#reqid', '0'], ['#msg', 'Web Activity end (section 200, # SysD 1, Files 222, Bytes 343422089928, Errors 0, Aborted Files 0, Busy Files 0)']]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM