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

huangapple go评论77阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年3月7日 23:16:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/75663813.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定