You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Python标准正则re.match将重复匹配值收集到列表?

解决重复捕获组仅保留最后一个结果的问题

方法一:使用Python 3.10+的captures()方法

Python 3.10及以上版本的re.Match对象新增了captures(group)方法,可以返回指定命名组所有匹配结果的列表。你可以先通过re.fullmatch(确保整个字符串完全匹配)获取匹配对象,再用该方法提取所有捕获内容:

import re

s = '[1][2][5] and [3][8]'
pattern = r'^(?:\[(?P<x>\d+)\])+ and (?:\[(?P<y>\d+)\])+$'
match_obj = re.fullmatch(pattern, s)
result = {
    'x': match_obj.captures('x'),
    'y': match_obj.captures('y')
}
print(result)  # 输出: {'x': ['1', '2', '5'], 'y': ['3', '8']}

方法二:兼容低版本Python的通用方案

如果你的Python版本低于3.10,可以先匹配整个字符串的结构,捕获x和y对应的区域片段,再分别从这些片段中提取所有数字,无需手动拆分原字符串:

import re

s = '[1][2][5] and [3][8]'
# 匹配整体结构,捕获x区域和y区域的原始字符串
pattern = r'^(?P<x_part>(?:\[\d+\])+) and (?P<y_part>(?:\[\d+\])+)$'
match_obj = re.match(pattern, s)
x_part = match_obj.group('x_part')
y_part = match_obj.group('y_part')

# 从捕获的区域中提取所有数字
result = {
    'x': re.findall(r'\[(\d+)\]', x_part),
    'y': re.findall(r'\[(\d+)\]', y_part)
}
print(result)  # 输出: {'x': ['1', '2', '5'], 'y': ['3', '8']}

为什么原方法失效?
正则引擎中,重复的捕获组(比如(?:\[(?P<x>\d+)\])+)每次匹配都会覆盖之前的捕获结果,只会保留最后一次匹配的内容,这是默认行为,所以你原代码只能拿到最后一个数字。

内容的提问来源于stack exchange,提问作者Fomalhaut

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 16:50:21