Python re.findall匹配Telegram消息正则返回空列表求助
Python正则re.findall返回空列表问题解决
问题原因
- 正则默认不匹配换行符:Python
re模块中,.默认不会匹配换行符\n,而目标文本里「⏰ Timeframe M5」和「⏰ Timeframe M15」之间包含多行内容,导致原正则无法匹配中间的换行区域。 - 变量名错误:代码中
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
相关产品推荐
相关产品推荐

