Don't want to do the regexp test twice

Eddie Corns eddie at holyrood.ed.ac.uk
Fri Jul 25 12:35:38 EDT 2003


Egbert Bouwman <egbert.list at hccnet.nl> 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 pat.search(line):
>        mat = pat.search(line)
>    elif ... :
>       ...
>    else ...:
>       ...
>Is there a way to to do this job with only one pat.search(line) ?
>Of course I can do this:

>for line in mylist:
>    mat = pat.search(line)
>    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 = re.search (...)
  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
    el...

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.

Eddie




More information about the Python-list mailing list