[英]python pattern match and process
我試圖用一堆線來解析日志。 我試圖從實時跟蹤中解析的行(文件尾部的那一行)是以“ Contact”開頭的那一行。 實際上,我需要使用方括號之間的所有內容作為[2a00:c30:7141:230:1066:4f46:7243:a6d2]中的數字,並用方括號(56791)后的雙點分隔數字作為變量。 我已經嘗試過機智的正則表達式搜索,但是我不知道該如何處理。
Contact: "200" <sip:200@[2a00:c30:7141:230:1066:4f46:7243:a6d2]:56791;transport=udp;registering_acc=example_com>;expires=600
如果格式始終相同:
for line in logfile:
if "Contact" in line:
myIPAddress=line.split('[')[1].split(']')[0]
myPort=line.split(']:')[1].split(';')[0]
使用正則表達式這樣做
import re
logfile = open('xxx.log')
p = r'\[([a-f0-9:]+)\]:([0-9]+)'
pattern = re.compile(p)
for line in logfile:
if line.startswith('Contact:'):
print pattern.search(line).groups()
logfile.close()
如果通過tail -f $logfile
類的東西獲取新條目,則可以將其輸出傳遞給此:
import re
import sys
for line in sys.stdin:
m = re.match(r'Contact: .*?\[(.*?)\]:(\d+)', line)
if m is not None:
address, port = m.groups()
print address, port
基本上讀取標准輸入中出現的每一行,並嘗試查找您感興趣的項目。如果某行不匹配,則不顯示任何內容。
data =re.search(r'Contact: .*?\[(.*?)\]:(\d+)', line_in_file)
if match:
temp=line_in_file.split('[')
temp1=temp[1].split(';')
hexValues = re.findall('[a-f0-9]', temp1[0])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.