How could one convert this to Python? The regex is used to match ipv4 addresses, but is there a better way to match this?
if ($line =~ m{\s+id\s+(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3}),\s+data\s+(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3}),\s+Type Transit\s+(\d{1,2})}) {
$id = "$1.$2.$3.$4";
$data = "$5.$6.$7.$8";
}
match = re.search(r"\s+id\s+(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3}),\s+data\s+(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3}),\s+Type Transit\s+(\d{1,2})", subject)
if match:
id = ".".join(match.group(1,2,3,4))
data = ".".join(match.group(5,6,7,8))
else:
# Match attempt failed
Is regex really the right tool to use for checking an IP address? Probably not.
Just split the string by the dots, and validate the resulting bits as being integers in the range 0-255. Almost certainly less effort for the computer than parsing the string with a regex.
Alternatively, try looking at some of the answers on this question: How to validate IP address in Python? -- there are plenty of good ways of validating an IP address that don't involve regex. (althoug having said that, at least one of the answers to that question does give a pretty comprehensive regex for both IPv4 and IPv6 addresses)
Hope that helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With