[python]Regex for matching ipv4 address

The regex pattern to match valid ipv4 addressing, which will include broadcast address, and also network id and direct broadcast address.

import re


subject = ["192.168.1.1",
           "0.1.1.1",
           "10.2.2.2",
           "256.233.23.1",
           "300.120.120.1",
           "172.16.1.0",
           "255.254.0.0",
           "224.1.1.1",
           "199.10.20.99",
           "10.256.2.44"]

pattern = "(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[1-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])"

regex = re.compile(pattern)
print([item for item in subject if regex.match(item)])

First octet, to be valid:
1. 25[0-5] matches between 250 and 255.
2. 2[0-4][0-9] matches between 200 and 249.
3. 1[0-9][0-9] matches between 100 and 199.
4. [1-9][0-9] matches between 10 and 99.
5. [1-9] matches between 1 and 9, no zero for the first octet.

Second to the last octet, to be valid:
1. 25[0-5] matches between 250 and 255.
2. 2[0-4][0-9] matches between 200 and 249.
3. 1[0-9][0-9] matches between 100 and 199.
4. [1-9][0-9] matches between 10 and 99.
5. [0-9] matches between 0 and 9, 0 allows for subsequent octets.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s