Regex to match key in YAML

前端 未结 3 1652
太阳男子
太阳男子 2020-12-21 17:40

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

3条回答
  •  我在风中等你
    2020-12-21 18:34

    You need this regex. I grouped it to key-value pair:

    ^\s*(?P\w+_flavor_id):\s*(?P\d+)
    

    Python demo: https://repl.it/Lk5W/0

    import re
    
    regex = r"^\s*(?P\w+_flavor_id):\s*(?P\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')))
    

提交回复
热议问题