使用Regex解析Python中的日志文本

2024-04-18 11:23:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样的格式:

att1="value 1" att2="value 2" att3="value 3" 

例如

level="Information" clientAddr="127.0.0.1" action="GetByName" message="Action completed" url="/customers/foo" method="GET" 

我可以用regex来解析这个吗?在值中,我没有任何嵌入的引号,但是我有空格


Tags: urlmessageinformationvalue格式actionlevelcompleted
2条回答

通过findall函数,可以得到双引号中的值。你知道吗

>>> import re
>>> m = 'level="Information" clientAddr="127.0.0.1" action="GetByName" message="Action completed" url="/customers/foo" method="GET"'
>>> s = re.findall(r'"([^"]*)"', m)
>>> for i in s:
...     print i
... 
Information
127.0.0.1
GetByName
Action completed
/customers/foo
GET
import xml.dom.minidom

def parsed_dict(attrs):
    return dict(xml.dom.minidom.parseString('<node {}/>'.format(attrs)).firstChild.attributes.items())

print parsed_dict('level="Information" clientAddr="127.0.0.1" action="GetByName" message="Action completed" url="/customers/foo" method="GET"')

{u'clientAddr': u'127.0.0.1', u'level': u'Information', u'url': u'/customers/foo', u'action': u'GetByName', u'message': u'Action completed', u'method': u'GET'}

相关问题 更多 >