Using a RegEx to match IP addresses in Python

后端 未结 13 2284
不思量自难忘°
不思量自难忘° 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
    
    0 讨论(0)
  • 2020-12-01 05:10
    def ipcheck():
    # 1.Validate the ip adderess
    input_ip = input('Enter the ip:')
    flag = 0
    
    pattern = "^\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}$"
    match = re.match(pattern, input_ip)
    if (match):
        field = input_ip.split(".")
        for i in range(0, len(field)):
            if (int(field[i]) < 256):
                flag += 1
            else:
                flag = 0
    if (flag == 4):
        print("valid ip")
    else:
        print('No match for ip or not a valid ip')
    
    0 讨论(0)
  • 2020-12-01 05:10

    IP address uses following authentication :

    1. 255 ---> 250-255
    2. 249 ---> 200-249
    3. 199 ---> 100-199
    4. 99 ---> 10-99
    5. 9 ---> 1-9

      import re    
      k = 0
      while k < 5 : 
          i = input("\nEnter Ip address : ")
          ip = re.match("^([1][0-9][0-9].|^[2][5][0-5].|^[2][0-4][0-9].|^[1][0-9][0-9].|^[0-9][0-9].|^[0-9].)([1][0-9][0-9].|[2][5][0-5].|[2][0-4][0-9].|[1][0-9][0-9].|[0-9][0-9].|[0-9].)([1][0-9][0-9].|[2][5][0-5].|[2][0-4][0-9].|[1][0-9][0-9].|[0-9][0-9].|[0-9].)([1][0-9][0-9]|[2][5][0-5]|[2][0-4][0-9]|[1][0-9][0-9]|[0-9][0-9]|[0-9])$",i)
          k = k + 1 
          if ip:
              print ("\n=====================")
              print ("Valid IP address")
              print ("=====================")
              break
          else :
              print ("\nInvalid IP")
      else :
          print ("\nAllowed Max 5 times")
      

    Reply me if you have doubt?

    0 讨论(0)
  • 2020-12-01 05:13
    import re
    ipv=raw_input("Enter an ip address")
    a=ipv.split('.')
    s=str(bin(int(a[0]))+bin(int(a[1]))+bin(int(a[2]))+bin(int(a[3])))
    s=s.replace("0b",".")
    m=re.search('\.[0,1]{1,8}\.[0,1]{1,8}\.[0,1]{1,8}\.[0,1]{1,8}$',s)
    if m is not None:
        print "Valid sequence of input"
    else :
        print "Invalid input sequence"
    

    Just to keep it simple I have used this approach. Simple as in to explain how really ipv4 address is evaluated. Checking whether its a binary number is although not required. Hope you like this.

    0 讨论(0)
  • 2020-12-01 05:19

    You are trying to use . as a . not as the wildcard for any character. Use \. instead to indicate a period.

    0 讨论(0)
  • 2020-12-01 05:20

    Using regex to validate IP address is a bad idea - this will pass 999.999.999.999 as valid. Try this approach using socket instead - much better validation and just as easy, if not easier to do.

    import socket
    
    def valid_ip(address):
        try: 
            socket.inet_aton(address)
            return True
        except:
            return False
    
    print valid_ip('10.10.20.30')
    print valid_ip('999.10.20.30')
    print valid_ip('gibberish')
    

    If you really want to use parse-the-host approach instead, this code will do it exactly:

    def valid_ip(address):
        try:
            host_bytes = address.split('.')
            valid = [int(b) for b in host_bytes]
            valid = [b for b in valid if b >= 0 and b<=255]
            return len(host_bytes) == 4 and len(valid) == 4
        except:
            return False
    
    0 讨论(0)
提交回复
热议问题