Regex to match key in YAML

前端 未结 3 1643
太阳男子
太阳男子 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:32

    You can use this regex:

    \b[^_\n]+_flavor_id:\s*(\d+)

    Click for Demo

    Regex Explanation:

    • \b - word boundary
    • [^_\n]+ - 1+ occurrences of any character which is not an _ nor a newline character
    • _flavor_id: - matches _flavor_id: literally
    • \s* - matches 0+ occurences of a white space character
    • (\d+) - matches and captures 1+ digits. This is the value that you needed.

    I am not well versed with python but regex101 allows us to generate the code. So, I am pasting the code here which you can use.

    import re
    
    regex = r"\b[^_\n]+_flavor_id:\s*(\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")
    
    matches = re.finditer(regex, test_str)
    
    for matchNum, match in enumerate(matches):
        matchNum = matchNum + 1
    
        print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))
    
        for groupNum in range(0, len(match.groups())):
            groupNum = groupNum + 1
    
            print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))
    

    This is the output I got:

提交回复
热议问题