Python正则表达式键值匹配

问题描述 投票:2回答:2

我有一个我试图解析的文件,包括键值对。其中键以“ - ”开头,后跟字母字符,值如下图所示。

当我使用下面的正则表达式模式解析文件时,我很容易获得键和值,但是当值包含多个单词或引用数据(也匹配键值)时,我的模式匹配失败。我已经尝试了多次正则表达式模式匹配迭代但未能获得所需的输出。我设法找到一个正则表达式模式来匹配引用的文本'“(。*?)”',但无法同时使用这两种模式。任何有助于获得所需输出的帮助都非常感谢。

Keys and Values

我的代码(仅限第一行的所需结果):

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')]
regex python-3.x regex-greedy
2个回答
0
投票

这是你可以使用的最好的正则表达式: 改变你的投票永远不会太晚。

正则表达式:

(?<!\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

0
投票

你可以用

(-\w+)\s+("[^"]*"|.*?)(?=$|\s*-\w+\s)

regex demo

细节

  • (-\w+) - 第1组:-和1+字形
  • \s+ - 1+空格
  • ("[^"]*"|.*?) - 第2组:",除了"之外的0+字符,然后"或除了断行字符之外的任何0+字符,尽可能少,直至第一...
  • (?=$|\s*-\w+\s) - 字符串结尾或0+空格,-,1 +字chars和空格。

Regulex图:

enter image description here

Python demo

import re
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 = {}
for line in mystring.splitlines():
    key_value = re.findall(r'(-\w+)\s+("[^"]*"|.*?)(?=$|\s*-\w+\s)', line)
    print(key_value)

输出:

[('-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')]
© www.soinside.com 2019 - 2024. All rights reserved.