使用正则表达式python捕获字符串中的整数列表
我试图在字符串中捕获使用正则表达式python捕获字符串中的整数列表,python,regex,Python,Regex,我试图在字符串中捕获List[int](可能用逗号分隔的整数列表)。然而,我没有得到预期的结果 >>txt=''自动人脸定位是 人脸图像分析的许多应用,如人脸属性 (例如表情[64]和年龄[38])和面部特征 认可[45,31,55,11]。面部定位的狭义定义 可能是指传统的人脸检测[53,62],“ 输出 关于findall(r'[(\b\d{1,3}\b,)+]',txt) ['(', '6', '4', '3', '8', ')', '4', '5', ',', '3', '1', ',
List[int]
(可能用逗号分隔的整数列表)。然而,我没有得到预期的结果
>>txt=''自动人脸定位是
人脸图像分析的许多应用,如人脸属性
(例如表情[64]和年龄[38])和面部特征
认可[45,31,55,11]。面部定位的狭义定义
可能是指传统的人脸检测[53,62],“
输出
关于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]']
你可以尝试:
\[[\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]']
您可以在中找到上述代码的示例运行,您可以匹配1-3位数字。然后重复0+次,匹配逗号、0+空格和1-3位数字
\[\d{1,3}(?:, *\d{1,3})*]
匹配\[
{
匹配1-3位数字\d{1,3}
非捕获组(?:
,*\d{1,3}
关闭组并重复0多次)*
匹配]
]
如果所有边上都可以有更多的数字和空格,包括在换行符上继续序列:
\[\s*\d+(?:\s*,\s*\d+)*\s*]
['[64]', '[38]', '[45, 31, 55, 11]', '[53, 62]']
\[\s*\d+(?:\s*,\s*\d+)*\s*]