正则表达式匹配 YAML 中的键 [英] Regex to match key in YAML
本文介绍了正则表达式匹配 YAML 中的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个看起来像这样的 yaml ..!用户可以定义N个xyz_flovor_id
,其中_flovor_id
键是通用的.目的是获取 *_flavor_id
键并从中提取值.
I have a yaml which looks like this..! User can define N number of xyz_flovor_id
where _flovor_id
key will be common. Aim is to grab *_flavor_id
key and extract value out of it.
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
匹配的正则表达式.然而,当试图在代码中使用它时,它会抛出错误.这是我的代码.
I am able to figure the regex to match the _flovor_id
. however while trying to use this in code it's throwing Error.
here is my code.
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 文件(预期).之后立即回溯.
print value
is dumping entire YAML file (expected). Immediate traceback after that.
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
推荐答案
您需要这个正则表达式.我将它分组为键值对:
You need this regex. I grouped it to key-value pair:
^\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')))
这篇关于正则表达式匹配 YAML 中的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文