perl regex to python

Hamish Lawson hamish_lawson at yahoo.co.uk
Wed Feb 7 05:16:41 EST 2001


nlymbo at my-deja.com wrote:

> Hi all, in perl i would do this to pick apart a date string:
>
> if ($date_str =~ m#(\d+)/(\d+)/(\d+)#) {
>   print "month: $1, $day: $2, $year: $3\n";
> }
>
> How does one save the matches in a reg expression using Python??

Python's re module provides the functionality of Perl's regular
expressions. The main difference is that Python doesn't have special
syntax and variables for dealing with REs (m//, $1, etc.), preferring
to do it via functions, methods and objects.

The re module provides a search function which returns a match object
if the search was successful or None if not. The group() method of the
match object returns the specified matched group. (When specifying REs
it's often a good idea to use the r"" raw-string notation to prevent
expansion of backslashed characters by Python itself.)

    import re
    date_str = "Today is 02/07/2001"
    m = re.search(r"(\d+)/(\d+)/(\d+)", date_str)
    if m:
        print "month: %s, day: %s, year: %s" % \
            (m.group(1), m.group(2), m.group(3))

Since the groups in your example are being printed out in order, you
could use the groups() method instead to return a tuple of the matched
groups:

        print "month: %s, day: %s, year: %s" % m.groups()

If you were going to be matching dates in a number of candidate
strings, then you would probably want to compile the regular expression
into a matcher object first and then repeatedly call the matcher
object's own search() method:

    matcher = re.compile(r"(\d+)/(\d+)/(\d+)")
    m = matcher.search(date_str)

This is similar to Perl's 'o' modifier for m//, but demonstrates
Python's preference of having an explicit object to represent the
compiled RE.

Hamish Lawson


Sent via Deja.com
http://www.deja.com/



More information about the Python-list mailing list