如何用正则表达式拆分python中的括号列表?

时间:2016-02-01 23:03:19

标签: python regex python-2.7 split python-2.x

我试图在python中使用re模块来拆分表示列表的字符串。该列表用括号标识。

输入:

"[1]first[2]second[3]third" ... etc

期望的输出:

['first', 'second', 'third',...]

我目前的代码如下:

out = re.split('\[(.*?)\]', thelist)

它会返回以下内容,但如何获得所需内容?

['', '1', 'first', '2', "second", '3', 'third',...]

4 个答案:

答案 0 :(得分:2)

您可以使用正则表达式匹配[...]附带的数字,并删除空元素:

import re
p = re.compile(r'\[\d+\]')
test_str = "[1]first[2]second[3]third"
print([x for x in p.split(test_str) if x])
# => ['first', 'second', 'third']

请参阅IDEONE demo

您的代码返回了捕获的文本,因为re.split将所有捕获作为结果数组中的单独元素返回。

  

如果分隔符中有捕获组并且它在字符串的开头匹配,则结果将以空字符串开头。

另外,要删除第一个空元素,可以使用

res = p.split(test_str)
if not res[0]:
    del res[0]

答案 1 :(得分:1)

用完[2 :: 2]。这需要从第三个到结尾的每个条目,但只采用每一个条目。

答案 2 :(得分:1)

如果格式始终相同而且您没有在单词中使用括号,请使用findall并在每个结束括号后获取字符串:

s = "[1]first[2]second[3]third"

import re

print(re.findall("\](\w+)" ,s))
['first', 'second', 'third']

要处理空格等,你可以使用字符集:

s = "[1]first foo[2]second[3]third"

import re

print(re.findall("\]([\w\s]+)", s))
['first foo', 'second', 'third']

答案 3 :(得分:1)

如果你的字符串看起来像你描述的那样,你可以使用简单的正则表达式:

re.findall(r'[a-z]+', s)

findall会为您返回一个列表,因此无需split

输出:

['first', 'second', 'third']