首页 > 解决方案 > 如何在Python中获取与正则表达式模式匹配的所有子字符串

问题描述

我在 Python 中使用 RegEx,但在查找与给定模式匹配的所有子字符串时遇到了一些麻烦。例如:

import re 
pattern = '\d{8}[TRWAGMYFPDXBNJZSQVHLCKE]$' 
text = 'I want to match this two: 01234567A and this 89012345B' 

当我应用 RegEx 时,我希望同时获得89012345Band 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']

如您所见,这只返回最后一个匹配项。我错过了什么?我怎么能两者兼得?

标签: pythonregex

解决方案


推荐阅读