Python regex to match IP-address with /CIDR

11,086

Solution 1

(?:\d{1,3}\.){3}\d{1,3}(?:/\d\d?)?

Solution 2

\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

Solution 3

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)?

Solution 4

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

Solution 5

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.

Share:
11,086
asdasdasd
Author by

asdasdasd

Updated on June 04, 2022

Comments

  • asdasdasd
    asdasdasd almost 2 years
    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?

  • Tim
    Tim over 12 years
    400.123.34.56 is matched but not valid (but asdasdasd's regex has the same problem)
  • Dave
    Dave almost 12 years
    Just FYI, the '/' may need to be escaped in languages such as Javascript.
  • Mariosti
    Mariosti almost 5 years
    Even better: '\b(25[0-5]|2[0-4]\d\b|1\d\d|\d\d|\d)\b\.\b(?1)\b\.\b(?1)\b\‌​.\b(?1)\b\b(\/\d\d|\‌​/\d)?\b'