首页 > 解决方案 > 在 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',是否可以返回所有结果?

谢谢!

标签: pythonregexpipe

解决方案


“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']

推荐阅读