python IP validation REGex validation for full and partial IPs

后端 未结 2 371
遇见更好的自我
遇见更好的自我 2020-12-21 19:55

Im trying to validate the input to see if it a valid IP address(could be a partial one).

Acceptable input : 172, 172.112, 172.112.113, 172.112.113.114

Unacc

相关标签:
2条回答
  • 2020-12-21 20:17

    Maybe you could avoid to use regex and let python socket.inet_aton do the job :

    import socket
    
    try:
        socket.inet_aton(addr)
        # correct IP
    except socket.error:
        # bad IP
    

    For inet_aton, a valid IP address is something of the form :

           a.b.c.d
           a.b.c
           a.b
           a
    

    In all of the above forms, components of the dotted address can be specified in decimal, octal (with a leading 0), or hexadecimal, with a leading 0X). Addresses in any of these forms are collectively termed IPV4 numbers-and-dots notation. The form that uses exactly four decimal numbers is referred to as IPv4 dotted-decimal notation (or sometimes: IPv4 dotted-quad notation).

    source

    0 讨论(0)
  • 2020-12-21 20:20

    This regex would do the trick:

    ^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){0,3}$
    

    It ensures that the given numbers are in the correct range (0-255) and can have 1-4 parts.

    You can see it in action here: http://regexr.com?2va3j

    0 讨论(0)
提交回复
热议问题