从Multi解析行的正则表达式

2024-04-27 12:23:22 发布

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

我希望能够按照以下格式解析来自服务器控制台(多草图)的行:

"source" <[ignore]"username"> "message"

下面是一个聊天的例子:

^{pr2}$

我的第一个策略是使用这个正则表达式:

^(?P<source>\[[^\]]+\])?\s*<\[.+\](?P<sender>[^>]*)>\s*(?P<message>.*)$

如果在标签前面没有[username]的话,它就会失败

[Server] <Johndonne> hello everyone!

用于测试regi关于芬德尔(regex,line)获取包含参数的元组。 有什么想法吗?在


Tags: 服务器sourcemessagehelloserver格式username标签
2条回答

您可以通过在其周围放置一个零或一个量词(?)使其成为可选的,如下所示:

^(?P<source>\[[^\]]+\])?\s*<(?:\[[^\]]+\])?(?P<sender>[^>]*)>\s*(?P<message>.*)$

但是当输入字符串是[Chat] <[VIP][Owner]bit2shift> hey时,此模式将捕获[Owner]bit2shift在{}组中。您可能需要使用零个或多个限定符(*)对多个标记进行分组:

^{pr2}$

这将只捕获bit2shift组中的<sender>。在

使其可选:

In [23]: x = """[Server] <Johndonne> hello everyone!
[Chat] <[VIP][Owner]bit2shift> hey
[Chat] <[Mod]waisman> hello there
[Chat] <[Builder]bluesniper> hey john xD"""

In [24]: rx = re.compile('^(?P<source>\[[^\]]+\])?\s*<(?:\[.+\])?(?P<sender>[^>]*)>\s*(?P<message>.*)$')

In [25]: [rx.search(xi) for xi in x.split('\n')]
Out[25]:
[<_sre.SRE_Match at 0x6c3ba48>,
 <_sre.SRE_Match at 0x6c3b7e8>,
 <_sre.SRE_Match at 0x6c3bae0>,
 <_sre.SRE_Match at 0x6c3bb78>]

In [26]: [rx.search(xi).group() for xi in x.split('\n')]
Out[26]:
['[Server] <Johndonne> hello everyone!',
 '[Chat] <[VIP][Owner]bit2shift> hey',
 '[Chat] <[Mod]waisman> hello there',
 '[Chat] <[Builder]bluesniper> hey john xD']

相关问题 更多 >