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
""" regex for finding valid ip address """
import re
IPV4 = re.fullmatch('([0-2][0-5]{2}|\d{2}|\d).([0-2][0-5]{2}|\d{2}|\d).([0-2][0-5]{2}|\d{2}|\d).([0-2][0-5]{2}|\d{2}|\d)', '100.1.1.2')
if IPV4:
print ("Valid IP address")
else:
print("Invalid IP address")
You have to modify your regex in the following way
pat = re.compile("^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$")
that's because .
is a wildcard that stands for "every character"
regex for ip v4:
^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$
otherwise you take not valid ip address like 999.999.999.999, 256.0.0.0 etc
import re
st1 = 'This is my IP Address10.123.56.25 789.356.441.561 127 255 123.55 192.168.1.2.3 192.168.2.2 str1'
Here my valid IP Address is only 192.168.2.2
and assuming 10.123.56.25
is not a valid one as it is combined with some string and 192.168.1.2.3
not valid.
pat = r'\s(((25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])\.){3}((25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])\s|$))'
match = re.search(pat,st1)
print match.group()
================ RESTART: C:/Python27/Srujan/re_practice.py ================
192.168.2.2
This will grep the exact IP Address, we can ignore any pattern look like an IP Address but not a valid one. Ex: 'Address10.123.56.25', '789.356.441.561' '192.168.1.2.3'
.
Please comment if any modifications are required.
str = "255.255.255.255"
print(str.split('.'))
list1 = str.split('.')
condition=0
if len(list1)==4:
for i in list1:
if int(i)>=0 and int(i)<=255:
condition=condition+1
if condition!=4:
print("Given number is not IP address")
else:
print("Given number is valid IP address")
This works for python 2.7:
import re
a=raw_input("Enter a valid IP_Address:")
b=("[0-9]+"+".")+"{3}"
if re.match(b,a) and b<255:
print "Valid"
else:
print "invalid"