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

Python re.findall匹配Telegram消息正则返回空列表求助

Python正则re.findall返回空列表问题解决

问题原因

  1. 正则默认不匹配换行符:Python re 模块中,. 默认不会匹配换行符 \n,而目标文本里「⏰ Timeframe M5」和「⏰ Timeframe M15」之间包含多行内容,导致原正则无法匹配中间的换行区域。
  2. 变量名错误:代码中 re.findall(regex, example_text) 里的 example_text 应为定义好的 text_example,变量名不匹配会导致逻辑错误。

修正代码

import re

regex = r"⏰ Timeframe M5((\s+(.*)\s+){1,})⏰ Timeframe M15"
text_example = '''⏰ Timeframe M5


04:05 - EURUSD - PUT
05:15 - EURJPY - PUT
06:35 - EURGBP - PUT
07:10 - EURUSD - PUT
08:15 - EURJPY - PUT

⏰ Timeframe M15

06:35 - EURGBP - PUT
07:10 - EURUSD - PUT
08:15 - EURJPY - PUT '''

# 添加re.DOTALL标志让.匹配换行符,同时修正变量名
reg = re.findall(regex, text_example, re.DOTALL)
print(reg)

简化正则写法

如果仅需提取两段标记之间的内容,可简化正则以避免冗余捕获组:

import re

regex = r"⏰ Timeframe M5(.*?)⏰ Timeframe M15"
text_example = '''⏰ Timeframe M5


04:05 - EURUSD - PUT
05:15 - EURJPY - PUT
06:35 - EURGBP - PUT
07:10 - EURUSD - PUT
08:15 - EURJPY - PUT

⏰ Timeframe M15

06:35 - EURGBP - PUT
07:10 - EURUSD - PUT
08:15 - EURJPY - PUT '''

# 启用DOTALL并使用非贪婪匹配
result = re.findall(regex, text_example, re.DOTALL)
# 去除首尾空白后输出内容
print(result[0].strip())

内容的提问来源于stack exchange,提问作者Djoi Patrick Santos de Souza

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 19:15:34