我无法从正则表达式匹配项创建列表



我试图只提取"DELETE/[资源]"列表部分:

57.88.37.55 - - [01/Mar/2021:21:50:36 +0000] "DELETE /customers HTTP/1.1" 201 4730
244.240.70.241 - - [01/Mar/2021:21:50:36 +0000] "GET /users HTTP/1.1" 400 3081
16.102.244.72 - - [01/Mar/2021:21:50:36 +0000] "PATCH /users HTTP/1.1" 200 2344
78.7.87.158 - - [01/Mar/2021:21:50:36 +0000] "DELETE /parsers HTTP/1.1" 300 2897
77.51.66.200 - - [01/Mar/2021:21:50:36 +0000] "POST /lists HTTP/1.1" 200 3364
55.12.74.229 - - [01/Mar/2021:21:50:36 +0000] "GET /customers HTTP/1.1" 200 3927
194.115.77.20 - - [01/Mar/2021:21:50:36 +0000] "GET /events HTTP/1.1" 301 2249
95.62.102.64 - - [01/Mar/2021:21:50:36 +0000] "PATCH /events HTTP/1.1" 503 4334
6.36.213.6 - - [01/Mar/2021:21:50:36 +0000] "DELETE /alerts HTTP/1.1" 403 3533

使用以下代码:

patternHTTPMethod = re.compile(r'([D]w+s/w+)') #Expressão regular para identificar o método HTTP DELETE e o recurso acedido
lstHTTPMethodDel=[]
for line in fstring: 
lstHTTPMethodDel.append(patternHTTPMethod.search(line)[0])
print(lstHTTPMethodDel)

(fstring是我赋予上面列表的变量)

但是,唉,我收到以下错误:

lstHTTPMethodDel.append(patternHTTPMethod.search(line)[0])
TypeError: 'NoneType' object is not subscriptable
对于这个问题有什么想法和方法吗?

在访问匹配的字符串之前检查regex是否匹配:

patternHTTPMethod = re.compile(r'([D]w+s/w+)')
lstHTTPMethodDel=[]
for line in fstring:
match = patternHTTPMethod.search(line)
if match:
lstHTTPMethodDel.append(match[0])
print(lstHTTPMethodDel)

我找到了解决这个问题的方法,插入

for line in fstring: 
if patternHTTPMethodDel.search(line) is None:
continue
else:
lstHTTPMethodDel.append(patternHTTPMethodDel.search(line)[0])

将放入代码

最新更新