Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl to Python Regex

Tags:

python

regex

perl

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";
}
like image 658
Ethan Whitt Avatar asked Feb 25 '26 05:02

Ethan Whitt


2 Answers

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
like image 72
Tim Pietzcker Avatar answered Feb 27 '26 18:02

Tim Pietzcker


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.

like image 37
Spudley Avatar answered Feb 27 '26 17:02

Spudley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!