gpt4 book ai didi

Python Regex 在某些情况下需要很长时间

转载 作者:行者123 更新时间:2023-11-28 20:45:50 24 4
gpt4 key购买 nike

我编译了下面的模式

pattern = re.compile(
r"""
(?P<date>.*?)
\s*
(?P<thread_id>\w+)
\s*PACKET\s*
(?P<identifier>\w+)
\s*
(?P<proto>\w+)
\s*
(?P<indicator>\w+)
\s*
(?P<ip>\d+\.\d+\.\d+\.\d+)
\s*
(?P<xid>\w+)
\s*
(?P<q_r>.*?)
\s*\[
(?P<flag_hex>[0-9]*)
\s*
(?P<flag_char_code>.*?)
\s*
(?P<status>\w+)
\]\s*
(?P<record>\w+)
\s*
\.(?P<domain>.*)\.
""", re.VERBOSE
)

使用这个字符串

2/1/2014 9:34:29 PM 05EC PACKET 00000000025E97A0 UDP Snd 10.10.10.10 ebbe R Q [8381 DR NXDOMAIN] A (1)9(1)a(3)c-0(11) 19-330ff801(7)e0400b1(4)15e0(4)1ca7(4)2f4a(3)210(1)0(26)841f75qnhp97z6jknf946qwfm5(4)avts(6)domain(3)com(0)

成功了

In [4]: pattern.findall(re.sub('\(\d+\)', '.', x))
Out[4]:
[('2/1/2014 9:34:29 PM',
'05EC',
'00000000025E97A0',
'UDP',
'Snd',
'10.10.10.10',
'ebbe',
'R Q',
'8381',
'DR',
'NXDOMAIN',
'A',
'9.a.c-0.19-330ff801.e0400b1.15e0.1ca7.2f4a.210.0.841f75qnhp97z6jknf946qwfm5.avts.domain.com')]

问题是在某些情况下需要很长时间,不知道如何增强模式以消耗时间。

最佳答案

是的,您有一个案例 catastrophic backtracking ,也称为“邪恶的正则表达式”,在这里:

\s*
(?P<q_r>.*?)
\s*

这里:

\s*
(?P<flag_char_code>.*?)
\s*

在这里:

\s*
\.(?P<domain>.*)\.

.* 替换为 \S* 应该可以解决问题。

有关什么是邪恶的正则表达式以及为什么它是邪恶的更多信息,请查看这个问题:
How can I recognize an evil regex?

关于Python Regex 在某些情况下需要很长时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22205972/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com