Python 正则表达式键值匹配

Python Regex Key Value Matching

我正在尝试解析一个包含键值对的文件。其中键以“-”开头,后跟字母字符和继续它的值,如下图所示。

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

我的代码(仅第一行的期望结果):

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')]

您可以使用

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

参见regex demo

详情

  • (-\w+) - 第 1 组:- 和 1+ 个单词字符
  • \s+ - 1+ 个空格
  • ("[^"]*"|.*?) - 第 2 组:",除 " 以外的 0+ 个字符,然后是 " 或除换行符以外的任何 0+ 个字符,因为很少尽可能到第一个...
  • (?=$|\s*-\w+\s) - 字符串结尾或 0+ 个空格,-,1+ 个单词字符和一个空格。

正则图:

参见 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')]

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

原始正则表达式:

(?<!\S)-(\w+)\s+("[^"]*"|[^\s"-]+(?:\s+[^\s"-]+)*)(?!\S)

python 原始:

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