Python Regex解析来自Multicraft的行
我希望能够按照以下格式分析来自服务器控制台(Multicraft)的行:Python Regex解析来自Multicraft的行,python,regex,Python,Regex,我希望能够按照以下格式分析来自服务器控制台(Multicraft)的行: "source" <[ignore]"username"> "message" “源”消息 下面是聊天的一个示例: [Server] <Johndonne> hello everyone! [Chat] <[VIP][Owner]bit2shift> hey [Chat] <[Mod]waisman> hello there [Chat] <[Builder]blu
"source" <[ignore]"username"> "message"
“源”消息
下面是聊天的一个示例:
[Server] <Johndonne> hello everyone!
[Chat] <[VIP][Owner]bit2shift> hey
[Chat] <[Mod]waisman> hello there
[Chat] <[Builder]bluesniper> hey john xD
[Server]大家好!
[聊天]嘿
[聊天]你好
[聊天]嘿,john xD
我的第一个策略是使用这个正则表达式:
^(?P<source>\[[^\]]+\])?\s*<\[.+\](?P<sender>[^>]*)>\s*(?P<message>.*)$
^(?P\[[^\]]+\])?\s*]*)>\s*(?P.*)$
但如果用户名前没有[tag],则会失败,例如当文本字符串为:
[Server] <Johndonne> hello everyone!
[Server]大家好!
为了测试正则表达式,我使用re.findall(regex,line)获得一个带有参数的元组。
有什么想法吗?您可以通过在该部分周围放置一个零或一个量词(
?
)使其成为可选部分,如下所示:
^(?P<source>\[[^\]]+\])?\s*<(?:\[[^\]]+\])?(?P<sender>[^>]*)>\s*(?P<message>.*)$
这将只捕获
组中的bit2shift
将其设置为可选:
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']
[23]:x=“”[Server]大家好!
[聊天]嘿
[聊天]你好
[聊天]嘿,约翰
在[24]中:rx=re.compile('^(?P\[[^\]]+\])?\s*]*)>\s*(?P*)$)
在[25 ]中:[X.X.S分裂('\n)]中席席的搜索(Xi)
出[25]:
[,
,
,
]
在[26 ]:[X.X.SeLin('\n)]中席席的RX.Sql(Xi).GROUP()
出[26]:
['[Server]大家好,
[聊天]嘿,
“[聊天]你好”,
“[聊天]嘿,约翰xD”]
它在一个简单的python脚本上工作。让我们看看Multicraft是否能处理它。谢谢
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']