regular expression: perl ==> python

Fredrik Lundh fredrik at pythonware.com
Wed Dec 22 02:23:58 EST 2004


<les_ander at yahoo.com> 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 = re.search(..., line)
    if m:
        print "got", m.group(1)

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

    http://www.amk.ca/python/howto/regex/

</F> 






More information about the Python-list mailing list