I need an regex which will match following pattern a.b.c.d /nn
, for example 192.168.0.24 /32
.
Meanwhile I'd like to do some validations, so that in the octets the first number could be only 1 or 2, if the last 3 octets consist only 1 number it can be 0 too. In addition the numbers of octets should be up to 255. In the similar way for /nn, the first digit should be only from 1 to 3, but if it is 3, the second should be from 0 to 2, if the first is absence, then the only number should be from 1 to 9.
I could wrote pattern like this
(?<!\d)(?!0|4|5|6|7|8|9)\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3} /(?<!\d)(?!0|4|5|6|7|8|9)\d{1,2}
but for example 192.168.740.056 /39
matches it as well.
CodePudding user response:
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'))
CodePudding user response:
Does this work for you?
def find_ips(ip_string):
for match in re.finditer(r'(?P<ip>[12]\d*\.\d \.\d \.\d )\s /(?P<mask>\d )', ip_string):
octets = list(map(int, match.group('ip').split('.')))
if all(0 <= octet <= 255 for octet in octets) and int(match.group('mask')) <= 32 and octets[-1] > 0:
yield match.group()
# ips = ['192.168.0.1 /32', '22.22.22.22 /32']
ips = list(find_ips("ip1=8.8.8.8 /32; ip2=192.168.0.1 /32; ip3=22.22.22.22 /32; ip4=192.168.740.056 /39"))