python - 如何在Python中获取与正则表达式模式匹配的所有子字符串
问题描述
我在 Python 中使用 RegEx,但在查找与给定模式匹配的所有子字符串时遇到了一些麻烦。例如:
import re
pattern = '\d{8}[TRWAGMYFPDXBNJZSQVHLCKE]$'
text = 'I want to match this two: 01234567A and this 89012345B'
当我应用 RegEx 时,我希望同时获得89012345B
and 01234567A
,但我只获得最后一个值 ( 89012345B
)。到目前为止我尝试过的是:
match = re.search(pattern, text)
print(match.group())
>>> '89012345B'
match = re.finditer(pattern, text)
print([match.group() for match in matches])
>>> ['89012345B']
match = re.findall(pattern, text)
print(match)
>>> ['89012345B']
如您所见,这只返回最后一个匹配项。我错过了什么?我怎么能两者兼得?
解决方案
推荐阅读
- javascript - 是否可以使用方法对数组道具进行排序?
- python - 我希望扩展用户(供应商)只能在仪表板上查看他或她的产品、订单和客户
- node.js - 如果不使用 TZ 环境变量,节点如何确定时区?
- scala - 如何使用 JWT 令牌保护 Scala Play 端点
- python - pandas 数据框中的索引数据行,其顺序不是自然排序的
- windows - 在 Windows 上安装 go vouch-proxy 失败
- android - Android textview 没有向上滚动,没有受到限制
- python - Streamlit 和 ContainDS ImportError:初始化失败:错误的 git 可执行文件
- python - Pyautogui:图像验证
- pyspark - to_timetamp 未在 pyspark 中显示毫秒