首页 > 解决方案 > 使用正则表达式python捕获字符串中的整数列表

问题描述

我正在尝试List[int]在字符串中捕获(可能用逗号分隔的整数列表)。但是我没有得到预期的结果。

>>> txt = '''Automatic face localisation is the prerequisite step of 
facial image analysis for many applications such as facial attribute 
(e.g. expression [64] and age [38]) and facial identity
recognition [45, 31, 55, 11]. A narrow definition of face localisation 
may refer to traditional face detection [53, 62], '''

输出

>>> re.findall(r'[(\b\d{1,3}\b,)+]',txt)
['(', '6', '4', '3', '8', ')', '4', '5', ',', '3', '1', ',', '5', '5', ',', '1', '1', '5', '3', ',', '6', '2', ',']

捕获以下输出的表达式应该是什么。

预期输出:

['[64]', '[38]', '[45, 31, 55, 11]', '[53, 62]']

标签: pythonregex

解决方案


你可以试试:

\[[\d, ]*?]

上述正则表达式的解释:

图示

请在此处找到上述正则表达式的演示。

python中的示例实现

import re

regex = r"\[[\d, ]*?]"

test_str = ("Automatic face localisation is the prerequisite step of facial image analysis for many applications such as facial attribute (e.g. expression [64] and age [38]) and facial identity\n"
    "... recognition [45, 31, 55, 11]. A narrow definition of face localisation may refer to traditional face detection [53, 62]")

print(re.findall(regex, test_str))
# Outputs: ['[64]', '[38]', '[45, 31, 55, 11]', '[53, 62]']

您可以在此处找到上述代码的示例运行。


推荐阅读