如何从字符串中提取多次出现的dict?

时间:2017-05-29 04:38:01

标签: python regex dictionary

我试图从字符串中提取多次出现的python dict。目前我正在使用失败的正则表达式,因为它也匹配dict之间的数据。我还使用了非贪婪的正则表达式({.+?}),但它弄乱了嵌套的词典并将它们视为不同的词组。

示例字符串:

mystring = '(2017-05-29, { "mydict": [{ "hello": "world"}, {"hello2":"world2"}]};;/url/string, {"dict2":{"world":"hello"}}'

代码:

>>>import re
>>>match_data = re.compile('({.+})')
>>>match_data.findall(mystring.strip())
['{ "mydict": [{ "hello": "world"}, {"hello2":"world2"}]};;/url/string, {"dict2":{"world":"hello"}}']

预期产出:

['{ "mydict": [{ "hello": "world"}, {"hello2":"world2"}]}', '{"dict2":{"world":"hello"}}']    

1 个答案:

答案 0 :(得分:1)

正则表达式对于这个问题可能过于简单了。但是,一种可能的解决方案是匹配这些副作用:

s = '{ "mydict": [{ "hello": "wo}}rld"}, {"hello2":"world2"}]};;/url/string, {"dict2":{"world":"hello"}}'


number_of_parthesis = 0
start_index = -1
in_quotes = False

for i,c in enumerate(s):
    if c in ["\'", "\""]:
        if in_quotes:
            in_quotes = False
        else:
            in_quotes = True
    if in_quotes:
        continue
    if c == "{":
        number_of_parthesis += 1
        if start_index == -1:
            start_index = i
    if c == "}":
        number_of_parthesis -= 1
        if number_of_parthesis == 0:
            print(s[start_index:i+1])
            start_index = -1

结果是:

{ "mydict": [{ "hello": "wo}}rld"}, {"hello2":"world2"}]}
{"dict2":{"world":"hello"}}