小编典典

正则表达式以匹配YAML中的密钥

python

我有一个看起来像这样的Yaml
..!用户可以定义的N个xyz_flovor_id,其中_flovor_id关键将是常见的。目的是获取*_flavor_id密钥并从中提取价值。

  server:
    tenant: "admin"
    availability_zone: "nova"
    cpu_overcommit_ratio: 1:1
    memory_overcommit_ratio: 1:1
    xyz_flovor_id: 1
    abc_flavor_id: 2

我能够找到正则表达式来匹配_flovor_id。但是,在尝试在代码中使用它时会引发错误。这是我的代码。

def get_flavor_keys(params):
    pattern = re.compile(r'[^*]flavor_id')
    for key, value in params.iteritems():
        print value
        if key == 'server':
            if pattern.match(value):
                print 'test'

print value正在转储整个YAML文件(预期)。之后立即回溯。

Traceback (most recent call last):
  File "resource_meter.py", line 150, in <module>
    get_flavor_keys(items)
  File "resource_meter.py", line 15, in get_flavor_keys
    if pattern.match(value):
TypeError: expected string or buffer

阅读 367

收藏
2021-01-20

共1个答案

小编典典

您需要此正则表达式。我将其分组为键值对:

^\s*(?P<key>\w+_flavor_id):\s*(?P<value>\d+)

Python演示:https//repl.it/Lk5W/0

import re

regex = r"^\s*(?P<key>\w+_flavor_id):\s*(?P<value>\d+)"

test_str = ("  server:\n"
    "    tenant: \"admin\"\n"
    "    availability_zone: \"nova\"\n"
    "    cpu_overcommit_ratio: 1:1\n"
    "    memory_overcommit_ratio: 1:1\n"
    "    xyz_flavor_id: 1\n"
    "    abc_flavor_id: 2\n")

matches = re.finditer(regex, test_str, re.MULTILINE)

for matchNum, match in enumerate(matches):
    print ("{key}:{value}".format(key = match.group('key'), value=match.group('value')))
2021-01-20