Python-如何在忽略内部数组的同时将字符串拆分为数组?

时间:2019-07-07 00:05:08

标签: python arrays split

我有一个类似于以下内容的字符串:

string = "hello,2,test,1,[4,something,3],1,2"

当我用逗号分割字符串时,得到以下数组:

['hello', '2', 'test', '1', '[4', 'something', '3]', '1', '2']

如何有效地拆分原始字符串以获取以下内容:

['hello', '2', 'test', '1', '[4,something,3]', '1', '2']

3 个答案:

答案 0 :(得分:2)

使用正则表达式

import re re.split(r",\s*(?![^[]*])",string)

结果:

['hello', '2', 'test', '1', '[4,something,3]', '1', '2']

请注意,此答案假定没有嵌套的[]

答案 1 :(得分:0)

这是一种方法:

string = "hello,2,test,1,[4,something,3],1,2"
string2 = string.split(",")
res = []
temp = []
found = False

for item in string2:
    if (not(found)):
        if "[" in item:
            found = True
            temp = []
            temp.append(item[1:])
        else:
            res.append(item)

    else:
        if "]" in item:
            found = False
            temp.append(item[:-1])
            final = str(temp).replace("'", "")
            res.append(final)
        else:
            temp.append(item)

print(res)

输出:

['hello', '2', 'test', '1', '[4, something, 3]', '1', '2']

答案 2 :(得分:0)

您可以使用正则表达式:

import re

string = "hello,2,test,1,[4,something,3],1,2"
x = re.findall(r'\[[^\]]+\](?=,|\b)|[^,]+(?=,|\b)', string)

x包含['hello', '2', 'test', '1', '[4,something,3]', '1', '2']

在正则表达式中,我们有两种情况,用|(或)分隔。第一个可以处理较长的情况[something, in, brackets],第二个可以处理简单的情况。如果您不熟悉(?=,|\b)positive lookahead