簡體   English   中英

Python 正則表達式在列表中僅找到一項不是全部

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

我有一個小的 Python 腳本,它調用一個配置文件和一個列表。 該列表用作搜索配置文件的模式。 該列表只是 IP 地址腳本運行,但它只找到列表中的第一個 IP,它不會逐個搜索配置。

有人可以告訴我我錯過了什么嗎? 我試圖調用 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 實際上可以幫助您同時搜索列表中的所有項目:

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)

正如@DaveStSomeWhere 所述,如果不讀取文件數據,則需要在每個循環中將文件重置為其初始 position。

因此,您可以將文件內容讀取到變量中並在其中查找匹配項。

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))

或者只是你可以在沒有 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