Don't want to do the regexp test twice

Eddie Corns eddie at
Fri Jul 25 18:35:38 CEST 2003

Egbert Bouwman <egbert.list at> writes:

>While looping over a long list (with file records)
>I use an (also long) if..elif sequence.
>One of these elif's tests a regular expression, and 
>if the test succeeds, I want to use a part of the match.
>Something like this:

>pat = re.compile(r'...')
>for line in mylist:
>    if ... :
>        ....
>    elif ... :
>        ....
>    elif
>        mat =
>    elif ... :
>       ...
>    else ...:
>       ...
>Is there a way to to do this job with only one ?
>Of course I can do this:

>for line in mylist:
>    mat =
>    if  ...:
>        ....
>    elif ...:
>        ....
>    elif mat:
>        ...
>but the test is relevant in only a relatively small number of cases.    
>And i would like to know if there exists a general solution
>for this kind of problem.

Unless I'm missing something (as usual), how about:

def lookup_func (line, pat, mat):
  x = (...)
  if x:
    mat.append (x)
    return x

mat = []
for line in mylist:
    if  ...:
    elif ...:
    elif lookup_func (line, pat, mat):
        # data is in mat[-1]
	mat = []	# for next time

ie you abstract out the code that gets the match data and get it to tell you
whether it succeeded or not.  Depending on your requirements it may be able to
handle several such operations with the one lookup function.


More information about the Python-list mailing list