import re
regex = re.compile(r"\b(127\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)|0?10\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)|172\.0?1[6-9]\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)|172\.0?2[0-9]\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)|172\.0?3[01]\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)|192\.168\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)|169\.254\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)|::1|[fF][cCdD][0-9a-fA-F]{2}(?:[:][0-9a-fA-F]{0,4}){0,7}|[fF][eE][89aAbB][0-9a-fA-F](?:[:][0-9a-fA-F]{0,4}){0,7})(?:\/([789]|1?[0-9]{2}))?\b", flags=re.MULTILINE)
test_str = ("# loopback\n"
"127.0.0.0\n"
"127.0.0.0000 # only three digits supported here\n\n"
"# A\n"
"10.0.0.1/10\n"
"10.255.22.33\n\n"
"# B\n"
"172.17.100.155/32\n\n"
"# C\n"
"192.168.1.1\n"
"192.168.1.255\n\n"
"# IPv6\n"
"fc00:833e:d648:f196:5c6c:1d9a:a14b:0d59\n"
"fc01:67e5::6a66:34a7\n"
"FC02:5fcf:e093:bb10:ce77:b5c9::/112\n"
"fc03:49bd:b7c1:5685:fa0a:87e9::2/128\n"
"fc04:::2 hmpf\n"
"# Public IP addresses\n"
"0de9:b022:883f:2c3c:7dba:a184:7576:4531\n"
"04e4:e53b:0c2f:2990:27ad:0464:6dd3:b6b3\n"
"0319:3b4a:546e:d480:4814:f885:3396:bba2\n"
"5394:03f5:606f:273e:e343:d94a:610a:3f2e\n"
"63cd:ad1f:7ffb:62c7:cc17:6e20:9b59:2f7d\n\n"
"# More \"crap\"\n"
"30.168.1.255.1\n"
"127.1\n"
"192.168.1.256\n"
"-1.2.3.4\n"
"1.1.1.1.\n"
"3...3\n"
"255.255.255.255\n"
"0.0.0.0\n"
"1.1.1.01\n"
"192.99.16.30\n\n"
"# decimal vs. octal mix\n"
"172.032.33.33\n"
"172.033.33.33\n\n"
"# octal - not supported here\n"
"0254.0021.0062.0041\n\n"
"# link-local addresses IPv4\n"
"169.254.1.0\n"
"169.254.254.255\n\n"
"# link-local addresses IPv6\n"
"fe90:1234::/64\n"
"feaf:ffff::/128\n"
"febf:ffff:ffff:ffff:ffff:ffff:ffff:ffff\n")
matches = regex.finditer(test_str)
for match_num, match in enumerate(matches, start=1):
print(f"Match {match_num} was found at {match.start()}-{match.end()}: {match.group()}")
for group_num, group in enumerate(match.groups(), start=1):
print(f"Group {group_num} found at {match.start(group_num)}-{match.end(group_num)}: {group}")
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Python, please visit: https://docs.python.org/3/library/re.html