sandbox/regex/regex_and_ipaddresses.py

56 lines
1.5 KiB
Python

import re
from typing import List
import ipaddress
entry = "test_range (2001:DB8:0:CD30::10-2001:DB8:0:CD30::100)"
entries: List[str] = [
"TEST_GEO_GROUP (82 countries)",
"Asia (50 countries)",
"Europe (55 countries)",
"IPv4-Private-10.0.0.0-8 (10.0.0.0/8)",
"IPv4-Private-172.16.0.0-12 (172.16.0.0/12)",
"IPv4-Private-192.168.0.0-16 (192.168.0.0/16)",
"OutsideIPv4DefaultRoute (0.0.0.0/0)",
"test_fqdnv4 (ad4.example.com)",
"brazil",
"chile",
"colombia",
"ecuador",
"test_fqdn (ad.example.com)",
"test_fqdnv4 (ad4.example.com)",
"test_fqdnv6 (ad6.example.com)",
"test_range (2001:DB8:0:CD30::10-2001:DB8:0:CD30::100)",
]
pattern = re.compile(
r"(^(?P<name>.+)\s\(((?P<countries>\d+\s\w+)|(?P<range>.+-.+)|(?P<fqdn>([a-zA-Z0-9._-])+)|(?P<ipv4>(\d+\.){3}\d+\/\d{1,3}))\)$)|^(?P<country>\w+$)"
)
for test_string in entries:
match = pattern.match(test_string)
if match:
print(f"Matched: {test_string}")
print("Groups:", match.groupdict())
else:
print(f"No match: {test_string}")
print("")
addresses: List[str] = [
"2001:DB8:0:CD30::100",
"192.168.0.0/16",
"::/0",
"2001:DB8::0DB8:800:200C:417A",
]
for addr in addresses:
try:
res = ipaddress.ip_address(addr)
print(res)
continue
except ValueError:
print(f"{addr} is not an address, trying network")
try:
res = ipaddress.ip_network(addr)
print(res)
except ValueError:
print(f"{addr} is not a network, ERROR~!!!")