Search code examples
pythonfilterstrip

filter IPaddress from list


I am a newbie to python I managed to pull data from an excel sheet using xlrd and put into a list and remove all white/empty spaces

I need to pull out the IP addresses from the list or remove all text. I have looked at strip regex and the module IP address but just seem overwhelmed, please help me find a solution.

ipList = ['Device name:', 'Management IPs:', 'Virtual Server IP', '10.100.33.131 (Prod)', '10.100.33.132 (Prod)', '10.100.33.133 (Prod)', '10.100.33.134 (Prod)', '10.100.33.148 (QA)', '10.100.33.149 (QA)', '10.100.33.150 (QA)', 'Scripted / HTTP Health check details', 'Name', 'iRule requirements']
#

Solution

  • You can use this regex to extract the IP from the list.

    import re
    
    ipList = ['Device name:', 'Management IPs:', 'Virtual Server IP', '10.100.33.131 (Prod)', '10.100.33.132 (Prod)', '10.100.33.133 (Prod)', '10.100.33.134 (Prod)', '10.100.33.148 (QA)', '10.100.33.149 (QA)', '10.100.33.150 (QA)', 'Scripted / HTTP Health check details', 'Name', 'iRule requirements']
    IP = []
    for element in ipList:
        ip = re.findall( r'[0-9]+(?:\.[0-9]+){3}', element)
        if len(ip) > 0:
            IP.append(ip)
    print IP