问题
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