简体   繁体   中英

Python regex finds only one item in list not all

I have a small Python script that calls a config file and a list. 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.

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.

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:

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.

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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