regular expression: perl ==> python

Fredrik Lundh fredrik at
Wed Dec 22 08:23:58 CET 2004

<les_ander at> wrote:

> i am so use to perl's regular expression that i find it hard
> to memorize the functions in python; so i would appreciate if
> people can tell me some equivalents.
> 1) In perl:
> $line = "The food is under the bar in the barn.";
> if ( $line =~ /foo(.*)bar/ ) { print "got <$1>\n"; }
> in python, I don't know how I can do this?
> How does one capture the $1? (I know it is \1 but it is still not clear
> how I can simply print it.

in Python, the RE machinery returns match objects, which has methods
that let you dig out more information about the match.  "captured groups"
are available via the "group" method:

    m =, line)
    if m:
        print "got",

see the regex howto (or the RE chapter in the library reference) for more


More information about the Python-list mailing list