Python 使用正则表达式解析参数行,参数中有空格,但没有引号
可以使用正则表达式解析这样一行:Python 使用正则表达式解析参数行,参数中有空格,但没有引号,python,regex,Python,Regex,可以使用正则表达式解析这样一行: name=This is tricky pos=81 key=4565 count=1 pass=a_23 find=2 分组 ('name=This is tricky', 'pos=81'...) 您可以使用将返回以下结果的\w+=拆分文本: >>> re.split(r'(\w+=)',s) ['', 'name=', 'This is tricky ', 'pos=', '81 ', 'key=', '4565 ', 'count=
name=This is tricky pos=81 key=4565 count=1 pass=a_23 find=2
分组
('name=This is tricky', 'pos=81'...)
您可以使用将返回以下结果的
\w+=
拆分文本:
>>> re.split(r'(\w+=)',s)
['', 'name=', 'This is tricky ', 'pos=', '81 ', 'key=', '4565 ', 'count=', '1 ', 'pass=', 'a_23 ', 'find=', '2']
然后在列表中使用zip
,连接相关元素:
>>> sp=re.split(r'(\w+=)',s)[1:]
>>> [''.join(i) for i in zip(sp[0::2],sp[1::2])]
['name=This is tricky ', 'pos=81 ', 'key=4565 ', 'count=1 ', 'pass=a_23 ', 'find=2']