Python正则表达式: search from right to left by delimiter,然后在分隔符左侧部分从右向左搜索

标签 python regex

示例:

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/

相关文章:

python - 将两个词典合并在一起并将 None 添加到所需位置

python - 通过套接字发送网络摄像头

python - 从 Tensorflow 中的模型检查点将损失值加载到 numpy.array

python - biopython - Entrez.esearch() 查询翻译与我的查询不符

python - 用指向 URL 的链接替换文本中的 URL

python - Django-slack 无法发送机器人消息

java - 限制数字之间有小数

regex - sed 替换,包括换行符

c++ - 使用 QRegExp 从 URL 中提取文件名

javascript - 正则表达式:匹配字符串外的字符串对