简体   繁体   English

Python 正则表达式在列表中仅找到一项不是全部

[英]Python regex finds only one item in list not all

I have a small Python script that calls a config file and a list.我有一个小的 Python 脚本,它调用一个配置文件和一个列表。 The list is used as the pattern to search the config file.该列表用作搜索配置文件的模式。 The list is just IP addresses The script runs but it only finds the first IP on the list it doesn't step through each one to search the config.该列表只是 IP 地址脚本运行,但它只找到列表中的第一个 IP,它不会逐个搜索配置。

Can someone tell me what I'm missing?有人可以告诉我我错过了什么吗? I have tried to call a function but it still only finds the first IP on the list.我试图调用 function 但它仍然只找到列表中的第一个 IP。

import re
list=['10.100.81.118',
'10.100.81.113',
'10.100.81.112',
'10.100.81.117',
'10.100.81.9',
'10.100.81.116',
'10.100.81.114',
'10.100.81.115',
'10.100.81.111',
'10.100.81.10',
'10.100.81.1']

config=open('show_run.txt','r')

for items in list:
    for answers in config:
        re2 = re.findall(items, answers, re.MULTILINE)
        if re2:
            print('\n'.join(re2))

Regex can actually help you search for all of the items in your list at the same time: Regex 实际上可以帮助您同时搜索列表中的所有项目:

import re
my_list = ['10.100.81.118', '10.100.81.113', '10.100.81.112',
         '10.100.81.117', '10.100.81.9', '10.100.81.116',
         '10.100.81.114', '10.100.81.115', '10.100.81.111',
         '10.100.81.10', '10.100.81.1']

pattern = r'({})'.format('|'.join(my_list))
print (pattern)

example1 = 'this is an ip address: 10.100.81.9 10.100.81.9 and this is another: 10.100.81.113'
example2 = 'this is an ip address: 10.100.81.10 and this is another: 10.100.81.113'
config = [example1, example2]

for answers in config:
    res = re.findall(pattern, answers)
    print (res)

As mentioned by @DaveStSomeWhere, the file needs to be reset to its initial position in each loop if not reading the file data.正如@DaveStSomeWhere 所述,如果不读取文件数据,则需要在每个循环中将文件重置为其初始 position。

So, you could do is read the file content to a variable and look in that to find a match.因此,您可以将文件内容读取到变量中并在其中查找匹配项。

import re
ip_list=['10.100.81.118', '10.100.81.113', '10.100.81.112',
'10.100.81.117', '10.100.81.9', '10.100.81.116',
'10.100.81.114', '10.100.81.115', '10.100.81.111',
'10.100.81.10', '10.100.81.1']

config= open('show_run.txt', 'r')
configdata = config.read()

for items in ip_list:
    re2 = re.findall(items, configdata, re.MULTILINE)
    if re2:
        print('\n'.join(re2))

OR simply you could do this without the re module:或者只是你可以在没有 re 模块的情况下做到这一点:

for items in ip_list:
    if items in configdata:
        print('\n'.join(items))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM