python - 在 Python Regex 中使用管道字符返回多个结果
问题描述
使用管道字符时|
,如何让我的正则表达式中定义的所有结果返回?
还是该.search()
方法只返回找到的第一个结果?
这是我的代码:
import re
bat.Regex = re.compile(r'Bat(man|mobile|copter|bat)')
matchObject = batRegex.search('Batmobile lost a wheel, Batcopter is not a chopper, his name is Batman, not Batbat')
print(matchObject.group())
只返回第一个结果'batmobile'
,是否可以返回所有结果?
谢谢!
解决方案
“re”模块请参考官方文档
链接的文档摘录:
- findall() 匹配所有出现的模式,而不是像 search() 那样只匹配第一个。
re.search(pattern, string, flags=0)
扫描字符串寻找正则表达式的第一个位置,并返回对应的匹配对象。re.findall(pattern, string, flags=0)
返回字符串中模式的所有非重叠匹配,作为字符串列表(此处注意:不是只有一个匹配的匹配对象)
import re
batRegex = re.compile(r'Bat(man|mobile|copter|bat)')
results = batRegex.findall('Batmobile lost a wheel, Batcopter is not a chopper, his name is Batman, not Batbat')
results
输出:
['mobile', 'copter', 'man', 'bat']
推荐阅读
- python-3.x - 如何将目录添加到路径?
- elasticsearch - 随时随地搜索的主体
- xml - 使用 xmlstarlet 编辑属性值
- microsoft-graph-api - 使用图形 API 仅返回 SharePoint 列表中的选定列并将 Graph.List 转换为 DataTable
- jmeter - 有没有办法在 API 测试时在 JMeter 中跟踪 HATEOAS 链接/重用响应?
- scala - Scala circe derivedUnwrapped 值类不适用于缺少的成员
- sql - SQL JSON - 从数组中获取特定值
- bash - 使用 wget 克隆网站的 Bash 脚本
- asp.net-mvc - 将字体真棒图标添加到 Html.ActionLink
- python - Matplotlib:具有两个不同 y 轴的 2D 子图