Python regular expression: search from right to left by delimiter, then search from right to left in the left part of the delimiter

Question:

Example:

aaa_bbb_ /xyz=uvw,ccc=height:18y,weight:1xb,ddd=19d

The end goal is to parse it into a dictionary:

{'aaa_bbb_ /xyz':'uvw','ccc':'height:18y,weight:1xb','ddd':19d}

The rule is:

search for "=" from the right, split by "=".
To the left of the "=" sign, search for "," from right to left again, content between "," and "=" is the key: ‘ddd’, and content to the right of "=" is the value: ’19d’.

After this is done, repeat the step in the remainder of the string

aaa_bbb_/xyz=uvw,ccc=height:18y,weight:1xb

The string contains at least one key:value pair(s). Character ,, as well almost all special character, can exist in the value as the example suggest.

Asked By: John

||

Answers:

You can try this:

import re

s = "aaa_bbb_ /xyz=uvw,ccc=height:18y,weight:1xb,ddd=19d"
res = re.findall(r"(.*?)=(.*?)(?:,|$)", s[::-1])
d = {k[::-1] : v[::-1] for v, k in res}
print(d)

It gives:

{'ddd': '19d', 'ccc': 'height:18y,weight:1xb', 'aaa_bbb_ /xyz': 'uvw'}
Answered By: bb1
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.