In Perl I would do something like this for taking different fields in a regexp, separating different fields by () and getting them using $
foreach $line (@lines)
{
$line =~ m/(.*?):([^-]*)-(.*)/;
$field_1 = $1
$field_2 = $2
$field_3 = $3
}
How could I do something like this in Python?
In Perl, you'd be much better off using an array than suffixing a bunch of scalars with numbers. E.g.
In Python, the
re
module returns a match object containing the capture-group information. So you could write:Then your matches would be available in
match.group(1)
,match.group(2)
, etc."Canonical" Python translation of your snippet...:
Importing
re
is a must (imports are normally done at the top of a module, but that's not mandatory). Precompiling the RE is optional (if you use there.search
function instead, it will compile your pattern on the fly) but recommended (so you don't rely on the module cache of compiled RE objects for your performance, and also in order to have a RE object and call its methods, which is more common in Python).You can use either the
match
method (which always tries matching from the start, whether or not your pattern starts with'^'
) or thesearch
method (which tries matching anywhere); with your given pattern they should be equivalent (but I'm not 100% sure).The
.groups()
method returns all matching groups so you can assign them all in one gulp (using a list in Python, just like using an array in Perl, would probably be more normal, but since you chose to use scalars in Perl you can do the equivalent in Python too).This will fail with an exception if any line does not match the RE, which is fine if you know they all do match (I'm not sure what's the behavior of your Perl but I think it would "reuse" the previous matching line's values instead, which is peculiar... unless, again you know all lines match;-). If you want to just skip non-matching lines, change the last statement to the following two:
Python supports regular expressions with the
re
module. There.search()
method returns aMatchObject
which has methods likegroup()
which you can use to retrieve the "capturing group" information.For example:
Just as an alternative example, python provides very nice support for named capture groups (in fact python pioneered support for named capture groups).
To use a named capture group, you just add
?P<the_name_of_the_group>
inside the opening parenthesis of the capture group.This allows you to get all of your matches in a dictionary very easily:
Here's the OP's example, modified to use named capture groups
Now
all_the_fields
is a dictionary with keys corresponding to the capture group names ("field1", "field2", and "field3") and the values corresponding to the contents of the respective capture groups.Why you should prefer named capture groups
Some good regex resources:
And don't forget that in Python, TIMTOWTDI ;)