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

Robert Brewer fumanchu at amor.org
Wed Mar 3 14:14:59 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.
> 
> Mostly what I've seen people do is to first test for the 
> match, and then 
> try matching again to get the results.  This would seem to be pretty 
> inefficient to me.
> >>> alist = ['boo','hoo','choo']
> >>> [re.match('choo',line) for line in calist if 
> re.match('choo',line)]
> [<_sre.SRE_Match object at 0x11e218>]

What's wrong with:

alist = ['boo','hoo','choo']
for line in alist:
    m = re.match('choo', line)
    if m:
        doSomethingWith(m.groups(0))


FuManChu




More information about the Python-list mailing list