我正在尝试分析一个包含键值对的文件。该键以“-”开头,后跟字母字符,并在其后跟值,如下图所示。
当我使用下面的正则表达式模式解析文件时,我很容易获得键和值,但是当值包含多个单词或带引号的数据(也与键值匹配)时,我的模式匹配失败。我曾尝试过多次进行正则表达式模式匹配,但未能获得所需的输出。我设法找到一个正则表达式模式来匹配引用的文本'“(。*?)”',但是无法同时使用两种模式。非常感谢获得以下所需输出的任何帮助。
我的代码(仅第一行需要的结果):
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')]
这是您可以使用的最佳正则表达式:
更改投票永远为时不晚。
正则表达式原始:
(?<!\S)-(\w+)\s+("[^"]*"|[^\s"-]+(?:\s+[^\s"-]+)*)(?!\S)
python raw:
r"(?<!\S)-(\w+)\s+(\"[^\"]*\"|[^\s\"-]+(?:\s+[^\s\"-]+)*)(?!\S)"
https://regex101.com/r/7bYN1A/1
键=组1
值=组2
(?<! \S )
-
( \w+ ) # (1)
\s+
( # (2 start)
" [^"]* "
| [^\s"-]+
(?: \s+ [^\s"-]+ )*
) # (2 end)
(?! \S )
基准测试
Regex1: (?<!\S)-(\w+)\s+("[^"]*"|[^\s"-]+(?:\s+[^\s"-]+)*)(?!\S)
Options: < none >
Completed iterations: 50 / 50 ( x 1000 )
Matches found per iteration: 10
Elapsed Time: 1.66 s, 1660.05 ms, 1660048 µs
Matches per sec: 301,196
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句