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.
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'}
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.
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'}