matching multiple regexs to a single line...

Bengt Richter bokr at oz.net
Wed Nov 13 00:23:00 EST 2002


On Tue, 12 Nov 2002 20:04:31 GMT, "Alexander Sendzimir" <lists at battleface.com> wrote:

>
>
>How does one match multiple regexs to a single line as in a compiler in
>Python?  I'm used to doing the following in Perl, for example:
>
>$line = <>;
>
>if ( $line ~= /regex1/ )
>{...}
>elsif ( $line ~= /regex2/ )
>{...}
>elsif (...)
>{ etc... }
>
>To do this in Python and be able to get at the match if a regex succeeds
>means I have to break up the if's 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.
>
Some might consider this cheating, but you could make a class instance
that you can use to grab a value in an expression for later use. E.g.,

 >>> import re
 >>> re1 = re.compile(r'one\s+(.*)')
 >>> re2 = re.compile(r'two\s+(.*)')
 >>> line = 'two This is message two.'

 >>> class V:
 ...     def __init__(self, v=None): self.v = v
 ...     def __call__(self, *v):
 ...         if v: self.v = v[0]
 ...         return self.v
 ...
 >>> v=V()


 >>> if v(re1.match(line)):
 ...     print v().group(1)
 ... elif v(re2.match(line)): 
 ...     print 'Use it differently:', v().group(1)
 ...
 Use it differently: This is message two.

Regards,
Bengt Richter



More information about the Python-list mailing list