Efficiently test for positive re.match then use the result?

Daniel Dittmar daniel.dittmar at sap.com
Thu Mar 4 05:54:06 EST 2004


elmlish wrote:
> I'm currently befuddled as to how to efficiently test for a positive
> re. match then use the results of that match in a function.

If you do this often, you might want to define a generator function:

def reMatches (iterator, patternString):
    rex = re.compile (patternString)
    for text in iterator:
        match = rex.match (text)
        if match:
            yield match

This can be used as
for match in reMatches (file (fname), 'href="([^"]*)"'):
    print match.group (0)

Variations include:
- reSearch to use the search instead of the match method
- allow to pass a string or a compiled regular expression as the second
parameter to reMatches
- find all the matches in a line and returning each with a separate yield

Daniel






More information about the Python-list mailing list