本文介绍了从包含转义字符的字符串中提取键值对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题基于:从包含键值对的字符串中获取python字典

我想获取键值对,其值对包含逃脱出来的等号.

I'd like to get key, value pairs with values that contain equals signs that are escaped out.

r = "key1=value1 key2=value2 request=http://www.pandora.com/json/music/artist/justin-moore?explicit\\=false uri=3DLoiRDsBABCAA9FvE1htRg\\=\\="
regex = re.compile(r"\b(\w+)=([^=]*)(?=\s\w+=\s*|$)")
d = dict(regex.findall(r))
print(d)

{'key2': 'value2', 'key1': 'value1'}

我似乎无法获得带有转义等号的值.我很确定([^ =] *)部分是错误的.我想我需要匹配任何不包含下一个key =

I cannot seem to get the values with escaped equals signs. I'm pretty sure the ([^=]*) part is wrong. I think I need to match on anything not containing the next key=

推荐答案

不要在字符串拆分有效的地方使用正则表达式:

Don't use a regular expression where string splitting will work:

dict(s.split('=', 1) for s in r.split())

演示:

>>> r = "key1=value1 key2=value2 request=http://www.pandora.com/json/music/artist/justin-moore?explicit\\=false uri=3DLoiRDsBABCAA9FvE1htRg\\=\\="
>>> dict(s.split('=', 1) for s in r.split())
{'key2': 'value2', 'key1': 'value1', 'request': 'http://www.pandora.com/json/music/artist/justin-moore?explicit\\=false', 'uri': '3DLoiRDsBABCAA9FvE1htRg\\=\\='}

这消除了转义=个字符的需要.

This removes the need to escape = characters.

这篇关于从包含转义字符的字符串中提取键值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 23:14