我正在学习正则表达式,特别是命名为capture组。
有一个问题,我无法弄清楚如何为函数findVul()编写if/else语句。
基本上,代码的工作方式或工作方式是findVul()通过data1和data2,它们已经添加到列表myDATA中。
如果regex找到整个命名组的匹配项,则应该打印出结果。它目前工作得很好。
代码:
import re
data1 = '''
dwadawa231d .2 vulnerabilities discovered dasdfadfad .One vulnerability discovered 123e2121d21 .12 vulnerabilities discovered sgwegew342 dawdwadasf
2r3232r32ee
'''
data2 = ''' d21d21 .2 vul discovered adqdwdawd .One vulnerability disc d12d21d .two vulnerabilities discovered 2e1e21d1d f21f21
'''
def findVul(data):
pattern = re.compile(r'(?P<VUL>(\d{1,2}|One)\s+(vulnerabilities|vulnerability)\s+discovered)')
match = re.finditer(pattern, data)
for x in match:
print(x.group())
myDATA = [data1,data2] count_data = 1
for x in myDATA:
print('\n--->Reading data{0}\n'.format(count_data))
count_data+=1
findVul(x)输出:
--->Reading data1
2 vulnerabilities discovered
One vulnerability discovered
12 vulnerabilities discovered
--->Reading data2现在,我想添加一个if / the语句来检查整个命名组是否有匹配项。
我试过这样的方法,但似乎不起作用。
代码:
def findVul(data):
pattern = re.compile(r'(?P<VUL>(\d{1,2}|One)\s+(vulnerabilities|vulnerability)\s+discovered)')
match = re.finditer(pattern, data)
if len(list(match)) != 0:
print('\nVulnerabilities Found!\n')
for x in match:
print(x.group())
else:
print('No Vulnerabilities Found!\n')输出:
--->Reading data1
Vulnerabilities Found!
--->Reading data2
No Vulnerabilities Found!如您所见,它不会打印data1中应该存在的漏洞。
有人能解释一下正确的方法吗?为什么我的逻辑是错误的。非常感谢:) !!
发布于 2018-10-12 05:11:10
在@AdamKG回复之后,我做了更多的研究。
我想使用re.findall()函数。
re.findall()将返回所有匹配子字符串的列表。在我的例子中,我的命名捕获组中有捕获组。这将返回一个包含元组的列表。
例如,以下使用data1的正则表达式:
pattern = re.compile(r'(?P<VUL>(\d{1,2}|One)\s+
(vulnerabilities|vulnerability)\s+discovered)')
match = re.findall(pattern, data)将返回一个包含元组的列表:
[('2 vulnerabilities discovered', '2', 'vulnerabilities'), ('One vulnerability
discovered', 'One', 'vulnerability'), ('12 vulnerabilities discovered', '12',
'vulnerabilities')]我的findVul()的最后代码:
pattern = re.compile(r'(?P<VUL>(\d{1,2}|One)\s+(vulnerabilities|vulnerability)\s+discovered)')
match = re.findall(pattern, data)
if len(match) != 0:
print('Vulnerabilties Found!\n')
for x in match:
print('--> {0}'.format(x[0]))
else:
print('No Vulnerability Found!\n')发布于 2018-10-12 03:37:27
问题是,re.finditer()返回一个迭代器,当您执行len(list(match)) != 0测试时,该迭代器将被计算;当您在for-循环中再次迭代它时,它已经耗尽,并且没有剩下的项。简单的修复方法就是在match = list(match)调用之后添加一个finditer()行。
https://stackoverflow.com/questions/52771827
复制相似问题