python - 使用正则表达式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]']
解决方案
你可以试试:
\[[\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]']
您可以在此处找到上述代码的示例运行。
推荐阅读
- bash - AppleScript 无法正确显示环境变量中的 CJK 字符
- prolog - 编写 Prolog 有序谓词
- image - 单击一个按钮会更改页面上的多个相关图像。如何适应多个按钮,每个按钮都有多个相关图像?
- python - 如何通过文件列表循环迭代工具?
- java - RecyclerView onScrolled 根本没有被解雇
- bean-io - 如何在 beanio 中引入新的流格式
- c# - c# 4.0 服务作为客户端连接信号器(1.2.2)集线器
- cordova - 如何在本地 Google 地图上以英里和公里为单位显示两个标记之间的距离?(科尔多瓦,离子 3)
- c++ - 如何修改正则表达式字符串
- c# - 游戏破坏Unity错误,太多玩家即使被摧毁也会破坏游戏