I have a string with valid python dictionary inside
data = "Some string created {'Foo': u'1002803', 'Bar': 'value'} string continue etc."
I need to extract that dict. I tried with regex but for some reason re.search(r"\{(.*?)\}", data) did not work. Is there any better way extract this dict?
解决方案
From @AChampion's suggestion.
>>> import re
>>> import ast
>>> x = ast.literal_eval(re.search('({.+})', data).group(0))
>>> x
{'Bar': 'value', 'Foo': '1002803'}
so the pattern you're looking for is re.search('({.+})', data)
You were supposed to extract the curly braces with the string, so ast.literal_eval can convert the string to a python dictionary . you also don't need the r prefix as { or } in a capturing group, () would be matched literally.