英文:
Python regular expression: search from right to left by delimiter, then search from right to left in the left part of the delimiter
问题
{'aaa_bbb_ /xyz':'uvw','ccc':'height:18y,weight:1xb','ddd':19d}
英文:
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.
答案1
得分: 3
你可以尝试这样做:
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'}
英文:
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'}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论