从有效的regex查询中获取None类型错误

2024-06-15 21:29:08 发布

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

我试图从程序的输出中提取osLinux 3.11 and newer)的值。我想到了这个:

import re

p0f = '''
--- p0f 3.08b by Michal Zalewski <lcamtuf@coredump.cx> ---

[+] Closed 3 file descriptors.
[+] Loaded 324 signatures from '/etc/p0f/p0f.fp'.
[+] Will read pcap data from file 'temp.pcap'.
[+] Default packet filtering configured [+VLAN].
[+] Processing capture data.

.-[ 10.0.7.20/37462 -> 216.58.209.229/443 (syn) ]-
|
| client   = 10.0.7.20/37462
| os       = Linux 3.11 and newer
| dist     = 0
| params   = none
| raw_sig  = 4:64+0:0:1460:mss*20,7:mss,sok,ts,nop,ws:df,id+:0
|
`----

.-[ 10.0.7.20/37462 -> 216.58.209.229/443 (mtu) ]-
|
| client   = 10.0.7.20/37462
| link     = Ethernet or modem
| raw_mtu  = 1500
|
`----


All done. Processed 1 packets.
'''


print p0f
os = re.match(r"os\\s*= (.*)", p0f).group(1)
print os

根据这个Regex101,我的正则表达式应该是正确的。但是我得到一个错误NoneType has no 'group'


Tags: andfromreclientdatarawoslinux
2条回答

如果您正在使用r,请不要转义\。这样做有效:

re.search(r"os\s*= (.*)", p0f).group(1)

你有两个问题:

  • 您使用的是re.match(),而您应该使用re.search()re.match()只与字符串的开始匹配。请参阅模块文档中的^{} vs. ^{}
  • 您在\s元字符上加倍了\\反斜杠,但使用的是r'..'原始字符串文字

这样做有效:

re.search(r"os\s*= (.*)", p0f)

演示:

>>> import re
>>> re.search(r"os\s*= (.*)", p0f).group(1)
'Linux 3.11 and newer'

相关问题 更多 >