In Python, there are several ways to "bind a name on the fly", for example, my old recipe for "assignment and control"; in this case, I would choose another such method (assuming that Python 2.6 needs minor changes if you are working with an old version of Python), something like:
import re pats_marks = (r'^A:(.*)$', 'FOO'), (r'^B:(.*)$', 'BAR') for line in lines: mo, m = next(((mo, m) for p, m in pats_mark for mo in [re.match(p, line)] if mo), (None, None)) if mo: print '%s: %s' % (m, mo.group(1)) else: print 'NO MATCH: %s' % line
Of course, you can correct many small details (for example, I chose instead of (.*) (.*) Instead of (.*?) As an equivalent group - they are equivalent, given the next $ immediately), so I chose a shorter form ;-) - you can precompile REs, set arguments differently than the pats_mark tuple (for example, with an index with an RE index), etc.
But the essential ideas, I think, are to make the data-driven structure and associate the correspondence object with the name "on the fly" with the subexpression for mo in [re.match(p, line)] , "loop" over the list of individual elements (genexps only binds names for the cycle, and not for the purpose - some consider the use of this part of the genexps specifications to be “complicated”, but I consider it a perfectly acceptable Python idiom, especially because it was considered at the time listcomps was used, it was assumed that the “ancestors” of genexps in in some sense were developed).
Alex martelli
source share