使用re.findall()进行模式匹配会产生不一致的结果

2024-05-29 10:21:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在从IRC服务器接收文本块,并且数据并非总是以一致的格式发送

这是我期待的格式

:hey!hey.tmi.twitch.tv PRIVMSG #stream :message here\r\n

我开发了这个正则表达式模式来匹配它:

:[^()]+![^()]+.tmi.twitch.tv PRIVMSG #[^()]+ :[^()]+\\r\\n

我这样做是为了将匹配项分配到一个列表中:

newlist = re.findall(':[^()]+![^()]+.tmi.twitch.tv PRIVMSG #[^()]+ :[^()]+\\r\\n',str(string))

但是,例如,当输入重复发送时(不经常发生,但确实发生)

:hey!hey.tmi.twitch.tv PRIVMSG #stream :message here\r\n:otherhey!otherhey!tmi.twitch.tv PRIVMSG #otherstream :othermessage here\r\n

它匹配整个字符串

所以! 我正在尝试合并这个正则表达式: ^[^PRIVMSG]*PRIVMSG[^PRIVMSG]*$ 使用另一个,这样findall将返回字符串中匹配完整模式的每个实例

但结果是我没有找到任何匹配项。 我错过了什么? 谢谢你的帮助


Tags: 字符串服务器messagestreamhere格式irc模式
1条回答
网友
1楼 · 发布于 2024-05-29 10:21:44

这是因为正则表达式中的量词表现得贪婪。让它不贪婪将使它工作

:[^()]+?![^()]+?.tmi.twitch.tv PRIVMSG #[^()]+? :[^()]+?\\r\\n

Demo

Python示例

import re
text=":hey!hey.tmi.twitch.tv PRIVMSG #stream :message here\r\n:otherhey!otherhey!tmi.twitch.tv PRIVMSG #otherstream :othermessage here\r\n"
print(re.findall(r":[^()]+?![^()]+?.tmi.twitch.tv PRIVMSG #[^()]+? :[^()]+?\r\n",text))

输出

[':hey!hey.tmi.twitch.tv PRIVMSG #stream :message here\r\n',
 ':otherhey!otherhey!tmi.twitch.tv PRIVMSG #otherstream :othermessage here\r\n']

相关问题 更多 >

    热门问题