how to handle repetitive regexp match checks

Matt Wette matt.wette at
Fri Mar 18 04:53:30 CET 2005

Over the last few years I have converted from Perl and Scheme to
Python.  There one task that I do often that is really slick in Perl
but escapes me in Python.  I read in a text line from a file and check
it against several regular expressions and do something once I find a match.
For example, in perl ...

     if ($line =~ /struct {/) {
       do something
     } elsif ($line =~ /typedef struct {/) {
       do something else
     } elsif ($line =~ /something else/) {
     } ...

I am having difficulty doing this cleanly in python.  Can anyone help?

     rx1 = re.compile(r'struct {')
     rx2 = re.compile(r'typedef struct {')
     rx3 = re.compile(r'something else')

     m = rx1.match(line)
     if m:
       do something
       m = rx2.match(line)
       if m:
         do something
         m = rx3.match(line)
         if m:
	  do something

(In Scheme I was able to do this cleanly with macros.)


More information about the Python-list mailing list