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
Unacceptable input: 1724,172.11113 etc etc
Heres a function that I created to check it (however it validates unacceptable input like 1724 which I cant seem to fix..please help)
def ipcheck(ip):
ippattern_str = '(([1-2]?[\d]{1,2}\.?){0,1}(\.[1-2]?[\d]{1,2}){0,1}(\.[1-2]?[\d]{1,2}\.){0,1}(([1-2]?[\d]{1,2}[\D\W]*)'
ippattern = re.compile(ippattern_str)
# ippattern is now used to call match, passing only the ip string
global matchip
matchip = ippattern.match(ip)
return matchip
ip = sys.argv[1]
ipcheck(ip)
print matchip
I feel like maybe I need to use anchors properly? Ive tried everything to my best knowledge, any help would be appreciated.
Maybe you could avoid to use regex and let python socket.inet_aton do the job :
For inet_aton, a valid IP address is something of the form :
source
This regex would do the trick:
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