2014-06-06 114 views
-1

您好我有一個日誌數據匹配詞語括號並提取值

IPADDRESS['192.168.0.10'] - - PlATFORM['windows'] - - BROWSER['chrome'] - - EPOCH['1402049518'] - - HEXA['0x3c0593ee'] 

我想用正則表達式

例如以提取括號內的相應值(不工作)

ipaddress = re.findall(r"\[(IPADDRESS[^]]*)",output) 

輸出繼電器:

ipaddress = 192.168.0.10 

回答

2

你可以簡單地讓所有的元素像這樣

print dict(re.findall(r'([a-zA-Z]+)\[\'(.*?)\'\]', data)) 

輸出字典

{'BROWSER': 'chrome', 
'EPOCH': '1402049518', 
'HEXA': '0x3c0593ee', 
'IPADDRESS': '192.168.0.10', 
'PlATFORM': 'windows'} 
+0

謝謝然而,我正在尋找一個接一個,我已經有了答案IPA DDRESS \ ['([^'\]] +)''PLATFORM \ ['([^'\]] +)'。再次感謝 –

+0

@DeepakTivari你是什麼意思?如果你不想一次全部使用,那麼你可以使用'finditer' – thefourtheye

0
s1 = "IPADDRESS['192.168.0.10'] - - PlATFORM['windows'] - - BROWSER['chrome'] - - EPOCH['1402049518'] - - HEXA['0x3c0593ee']" 

import re 

print re.findall('\[\'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\'\]',s1)[0] 
192.168.0.10 

要獲得所有在列表中:

s1 = "IPADDRESS['192.168.0.10'] - - PlATFORM['windows'] - - BROWSER['chrome'] - - EPOCH['1402049518'] - - HEXA['0x3c0593ee']" 

print re.findall('\[\'(.*?)\'\]',s1) 

['192.168.0.10', 'windows', 'chrome', '1402049518', '0x3c0593ee'] 


result=re.findall('\[\'(.*?)\'\]',s1) 

ipaddress, platform, browser, epoch, hexa = result # assign all variables 

print "ipaddress = {}, platform = {}, browser = {}, epoch = {}, hexa = {}".format(ipaddress,platform,browser,epoch,hexa) 


ipaddress = 192.168.0.10, platform = windows, browser = chrome, epoch = 1402049518, hexa = 0x3c0593ee