matching multiple regexs to a single line...
Trent Mick
trentm at ActiveState.com
Tue Nov 12 17:21:48 EST 2002
> On Tue, 12 Nov 2002 15:18:01 +0000, John Hunter wrote:
> > That's what I usually end up doing
> >
> > for line in myfile:
> > m = r1.match(line)
> > if m:
> > do_something()
> > break
> >
> > m = r2.match(line)
> > if m:
> > do_something_else()
> > break
> >
> >
[Alexander Sendzimir wrote]
> Thanks for your response. This is what I was afraid of. This seems really
> sloppy. You don't think there is any better way of doing such a thing? In
> the mean time, what you propose is exactly what I've been doing. Hmmmm.
A slight mod on John's code makes it seem pretty clean to me:
patterns = [re.compile('...'),
re.compile('...')]
for line in myfile:
for pattern in patterns:
match = pattern.match(line)
if match:
// do something with 'match'
break
else:
raise "none of the patterns matched"
This scales well for adding more patterns. I usually use named groups in
my Python regexs so the single "do something" block for matching any of
the patterns works itself out.
> ... because I haven't been able to get
> Python to make an assignment in an if-statement. In other words,
>
> if ( myMatch = re1.match( line ) ) :
> ...
> elif ( myMatch = re2.match( line ) ) :
> ...
>
> doesn't work for me. Perhaps I've missed something simple.
No, you didn't miss anything. You cannot use assignment in the test part
of a Python if-statement.
Trent
--
Trent Mick
TrentM at ActiveState.com
More information about the Python-list
mailing list