I'm slowly moving from Perl to Python, and trying to understand the best practices of using regular expressions.
I have the following Perl code - this code basically takes a string as input and spits out rearranged string as output, based on regex match and capture:
#!/usr/bin/env perl
use strict;
use warnings;
my $str = $ARGV[0] || die "Arg?";
my $result;
if($str =~ m/^\d{12}$/) {
$result = $str;
} elsif($str =~ m{^(\d{2})/(\d{2})/(\d{4})$}) {
$result = "${1}${2}0000${3}";
} elsif($str =~ m{^(\d{4})$}) {
$result = "01010000${1}";
} else {
die "Invalid string";
}
print("Result: $result\n");
What would be a good equivalent in Python 3?
I came up with the following so far, but seems inefficient to match twice in the elif part. Also seems inefficient to compile all regular expressions at the start.
#!/usr/bin/env python3
import re, sys
str = sys.argv[1]
p1 = re.compile('\d{12}')
p2 = re.compile('(\d{2})/(\d{2})/(\d{4})')
p3 = re.compile('(\d{4})')
if p1.match(str):
result = str
elif p2.match(str):
m = p2.match(str)
result = '%s%s0000%s' % (m.group(1), m.group(2), m.group(3))
elif p3.match(str):
m = p3.match(str)
result = '01010000%s' % (m.group(1))
else:
raise Exception('Invalid string')
print('Result: ' + result)
Given Python's motto of "There should be one-- and preferably only one --obvious way to do it" - any ideas / suggestions of what the one best way here would be?
Thank you in advance for any suggestions.
Best regards, -Pavel