示例:
aaa_bbb_ /xyz=uvw,ccc=height:18y,weight:1xb,ddd=19d
最终目标是将其解析为字典:
{'aaa_bbb_ /xyz':'uvw','ccc':'height:18y,weight:1xb','ddd':19d}
规则是:
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'.
完成此操作后,在字符串的其余部分重复该步骤
aaa_bbb_/xyz=uvw,ccc=height:18y,weight:1xb
该字符串至少包含一个键:值对。如示例所示,字符 、
以及几乎所有特殊字符都可以存在于值中。
最佳答案
你可以试试这个:
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)
它给出:
{'ddd': '19d', 'ccc': 'height:18y,weight:1xb', 'aaa_bbb_ /xyz': 'uvw'}
关于Python正则表达式: search from right to left by delimiter,然后在分隔符左侧部分从右向左搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75663813/