【发布时间】:2019-08-17 00:30:00
【问题描述】:
我有一个要解析的文件,其中包含键值对。键以“-”开头,后跟字母字符,然后是值,如下图所示。
当我使用以下正则表达式模式解析文件时,我很容易获得键和值,但是当值包含多个单词或引用数据(也与键值匹配)时,我的模式匹配失败。我已经尝试了正则表达式模式匹配的多次迭代,但未能获得所需的输出。我设法找到一个正则表达式模式来匹配引用的文本'"(.*?)"' 但无法同时使用这两种模式。非常感谢任何有助于获得以下所需输出的帮助。
我的代码(仅第一行所需的结果):
mystring = '''-desc none -type used -cost med -color blue
-desc none -msg This is a a message -name test
-desc "(-type old -cost high)" -color green'''
mydict = {}
item_num = 0
for line in mystring.splitlines():
quoted = re.findall('"(.*?)"', line)
key_value = re.findall('(-\w+\s+)(\S+)', line)
print(key_value)
### Output ###
[('-desc ', 'none'), ('-type ', 'used'), ('-cost ', 'med'), ('-color ', 'blue')]
[('-desc ', 'none'), ('-msg ', 'This'), ('-name ', 'test')]
[('-desc ', '"(-type'), ('-cost ', 'high)"'), ('-color ', 'green')]
### Desired Output ###
[('-desc ', 'none'), ('-type ', 'used'), ('-cost ', 'med'), ('-color ', 'blue')]
[('-desc ', 'none'), ('-msg ', 'This is a message'), ('-name ', 'test')]
[('-desc ', "(-type old -cost high)"), ('-color ', 'green')]
【问题讨论】:
-
检查ideone.com/YSw8Cr - 是否按预期工作?
-
这是惊人的正则表达式魔法!是的,完全按预期工作。您能否简要解释一下这里使用的正则表达式模式?谢谢。
标签: regex python-3.x regex-greedy