pythonpython-3.xregex

Tag-like (/x=y/yellow=flower) Pattern-Matching Regex Python


I need to match the information associated with each tag with a regex pattern. The tags here are not HTML but follow the format of: /x=y or

tags = "/yellow=flower/blue=sky"

What would be the regex pattern to yield this information?

I have tried:

linein = "/yellow=flower/blue=sky"
pattern = "^[A-Za-z0-9]{1}^[A-Za-z0-9]{1}"
p2 = re.findall(pattern, linein)

The expected output is:

yellow flower
blue sky

Solution

  • Your attempt has several issues:

    With the above points taken into account, your code would become:

    import re
    
    linein = "/yellow=flower/blue=sky"
    pattern = r"/(\w+)=(\w+)"
    lst = re.findall(pattern, linein)
    print(lst)  # [('yellow', 'flower'), ('blue', 'sky')]
    print(dict(lst))  # {'yellow': 'flower', 'blue': 'sky'}