Skip to main content
 首页 » 编程设计

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

2025年05月04日40sky-heaven

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

输入:

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

期望的输出:

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

我目前的代码如下:

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

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

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

请您参考如下方法:

您可以使用正则表达式来匹配包含在 [...] 中的数字,并通过以下方式删除空元素:

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

要使用 Python 3 中的数字获取输出,您可以使用

import re 
test_str = "[1]first[2]second[3]third" 
print( re.split(r'(?!^)(?=\[\d+])', test_str) ) 

参见 this Python 3 demo .

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

If there are capturing groups in the separator and it matches at the start of the string, the result will start with an empty string.

此外,要摆脱第一个空元素,您可以使用

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