匹配方括号前的单词并提取值

时间:2014-06-06 10:42:45

标签: python regex

您好我有一个日志数据

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 个答案:

答案 0 :(得分:2)

你可以简单地将所有元素都像这样的字典

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

<强>输出

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

答案 1 :(得分: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