Using a RegEx to match IP addresses in Python

后端 未结 13 2434
不思量自难忘°
不思量自难忘° 2020-12-01 04:58

I\'m trying to make a test for checking whether a sys.argv input matches the RegEx for an IP address...

As a simple test, I have the following...

imp         


        
13条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-01 05:06

    If you really want to use RegExs, the following code may filter the non-valid ip addresses in a file, no matter the organiqation of the file, one or more per line, even if there are more text (concept itself of RegExs) :

    def getIps(filename):
        ips = []
        with open(filename) as file:
            for line in file:
                ipFound = re.compile("^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$").findall(line)
                hasIncorrectBytes = False
                try:
                        for ipAddr in ipFound:
                            for byte in ipAddr:
                                if int(byte) not in range(1, 255):
                                    hasIncorrectBytes = True
                                    break
                                else:
                                    pass
                        if not hasIncorrectBytes:
                            ips.append(ipAddr)
                except:
                    hasIncorrectBytes = True
    
        return ips
    

提交回复
热议问题