help with simple regular expression grouping with re

Tim Peters tim_one at email.msn.com
Sun May 9 03:05:58 EDT 1999


[Bob Horvath]
> ...
> Well, I did a lot of searching around before and after my
> original post, and while findall seems to be the thing I want,
> I am using 1.5.1, which apparently does not have it.

Yes, re.findall is new in 1.5.2.

> I can upgrade my Linux system, but the system where it will
> ultimately run might be a different story.
>
> Is there a way to do the equivalent of findall on releases prior
> to having it?

How far back may you need to go?  Go back far enough, and you won't even
find re <wink>.

The source for findall is in re.py -- it's just a loop written in Python.
You can easily (provided you understand all the pieces first!) write the
same thing yourself.

Here's a Pythonic way to write modules that work with old and new releases:

import re
if hasattr(re, "findall"):
    # use the system-supplied version
    from re import findall
else:
    # oops!  not there -- implement it ourselves
    def findall(pattern, s):
        ...

Doesn't come up often, but painless to accommodate when it does.  Note that
"def" is an executable stmt, not a declaration (and ditto for "from ...
import ...", etc), so that if re.findall exists, the "def findall" isn't
executed.

one-of-these-days-it-will-all-look-so-simple-you'll-laugh<wink>-ly y'rs  -
tim






More information about the Python-list mailing list