m = re.findall("\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}",s)
How do I modify it so it will match not only IPv4, but also something with CIDR like 10.10.10.0/24
?
m = re.findall("\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}",s)
How do I modify it so it will match not only IPv4, but also something with CIDR like 10.10.10.0/24
?
(?:\d{1,3}\.){3}\d{1,3}(?:/\d\d?)?
\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(?:/\d{1,2}|)
Tested in Expresso
Matched:
64.33.232.212
64.33.232.212/30
/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(?:\/\d{1,2}|)/gm
–
Samaria ReGex ( ip_address with/without CIDR )
try this:
str1 = '0.0.0.0/0'
str2 = '255.255.255.255/21'
str3 = '17.2.5.0/21'
str4 = '29.29.206.99'
str5 = '265.265.20.20'
pattern = r"^((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]?)([/][0-3][0-2]?|[/][1-2][0-9]|[/][0-9])?$"
def check_ip(user_input):
match = re.search(pattern, user_input)
if match:
print(f"Yes, IP-address {match.string} is correct")
else:
print("No, IP-address is incorrect")
check_ip(str1)
check_ip(str2)
check_ip(str3)
check_ip(str4)
check_ip(str5)
output:
Yes, IP-address 0.0.0.0/0 is correct
Yes, IP-address 255.255.255.255/21 is correct
Yes, IP-address 17.2.5.0/21 is correct
Yes, IP-address 29.29.206.99 is correct
No, IP-address is incorrect
I had problems using a regex similar to yours. It was matching 1.2.3.4.5 (as 1.2.3.4) and 1111.2.3.4 (as 111.2.3.4). To avoid matching these, I added look ahead/behind assertions:
IP_RE = re.compile(r"(?<!\d\.)(?<!\d)(?:\d{1,3}\.){3}\d{1,3}(?!\d|(?:\.\d))")
IP_CIDR_RE = re.compile(r"(?<!\d\.)(?<!\d)(?:\d{1,3}\.){3}\d{1,3}/\d{1,2}(?!\d|(?:\.\d))")
The (?<!\d\.)(?<!\d)
checks that there isn't a number or octet before your first octet (ie: no 1 before 111.2.3.4).
And (?!\d|(?:\.\d))
checks that there isn't a number/octet after your last (ie: no .5 after 1.2.3.4).
Then, to check that the strings these match are valid IPs (eg: not 277.1.1.1), you can use
socket.inet_aton(ip) #raises exception if IP is invalid
There is an all_matching_cidrs(ip, cidrs)
function in netaddr's ip module; it takes an ip and matches it with a list of CIDR addresses.
Just did a really nice regex that also checks the ip format correctness, isn't to long, and matches subnet length optionally:
(25[0-5]|2[0-4]\d|1\d\d|\d\d|\d).(?1).(?1).(?1)\/?(\d\d)?
Append "(?:/\d{1,2})?"
.
That gets you r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(?:/\d{1,2})?"
for a pattern.
this extends your existing expression
\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\\\d{1,2}
Best answer I found is:
^([0-9]{1,3}\.){3}[0-9]{1,3}(\/([0-9]|[1-2][0-9]|3[0-2]))?$
© 2022 - 2024 — McMap. All rights reserved.