extracting key value pairs from a string containing escaped characters

淺唱寂寞╮ 提交于 2019-12-10 12:18:36

问题


this question builds on: get python dictionary from string containing key value pairs

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

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=


回答1:


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

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

Demo:

>>> 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.




回答2:


got it.

regex = re.compile(r"\b(\w+)=(.*?)(?=\s\w+=\s*|$)")


来源:https://stackoverflow.com/questions/22359216/extracting-key-value-pairs-from-a-string-containing-escaped-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!