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

Python中使用re.findall()以']]'为分隔符拆分字符串并保留分隔符

修正正则表达式以匹配完整条目

修改后的代码

Str = 'Floor_Live_Patterened_SpanPairs_1: [[-3, 0, 0, 5.5], [-3, 5.5, 0, 9.5]]Floor_Live_Patterened_SpanPairs_2: [[-3, 0, 0, 5.5], [-3, 9.5, 0, 13.5]]Floor_Live_Patterened_SpanPairs_3: [[-3, 5.5, 0, 9.5], [-3, 9.5, 0, 13.5]]'
from re import findall

# 基础方案:匹配从Floor开头到]]结束的完整条目
result = findall(r'Floor.*?]]', Str)
print(result)

# 精确方案:限定前缀格式,避免误匹配
result = findall(r'Floor_Live_Patterened_SpanPairs_\d+: \[\[.*?\]\]', Str)
print(result)

原正则问题分析

原正则[^\]\]]+\]\]?存在逻辑错误:

  • 字符集[^\]\]]等价于[^]],表示匹配任意非]的字符,遇到第一个单个]就会终止匹配,导致每个条目被拆分成两段。
  • \]\]?的写法无法改变前面字符集的匹配逻辑,因为前面的匹配已经在第一个]处停止。

方案说明

  1. 基础方案:r'Floor.*?]]'
    • Floor定位每个条目的起始标识
    • .*?是非贪婪匹配,会尽可能少地匹配字符,直到遇到第一个]]为止,确保完整捕获单个条目。
  2. 精确方案:r'Floor_Live_Patterened_SpanPairs_\d+: \[\[.*?\]\]'
    • \d+匹配条目编号的数字部分
    • 明确匹配前缀格式和开头的[[,进一步避免误匹配其他包含Floor和]]的无关内容。

运行结果

两种方案都会输出期望结果:

['Floor_Live_Patterened_SpanPairs_1: [[-3, 0, 0, 5.5], [-3, 5.5, 0, 9.5]]',
 'Floor_Live_Patterened_SpanPairs_2: [[-3, 0, 0, 5.5], [-3, 9.5, 0, 13.5]]',
 'Floor_Live_Patterened_SpanPairs_3: [[-3, 5.5, 0, 9.5], [-3, 9.5, 0, 13.5]]']

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 00:15:36