best way to do a series of regexp checks with groups

Mark Fanty markfanty at
Mon Jan 24 22:24:43 EST 2005

This is the kind of thing I meant.  I think I have to get used to writing 
small, light-weight classes.   You inspired this variation which is a little 
more verbose in the class definition, but less so in the use:

class Matcher:
  def search(self, r,s):
    self.value =,s)
    return self.value
  def __getitem__(self, i):

m = Matcher()

if'add (\d+) (\d+)', line):
  do_add(m[1], m[2])
elif'mult (\d+) (\d+)', line):
  do_mult(m[1], m[2])
elif'help (\w+)', line):

As for using regular expressions too much... they are why I've liked perl so 
much for quick file processing for years.  I don't like perl objects at all, 
which is why I'm trying python, but the re package has not been my favorite 
so far...

"Nick Craig-Wood" <nick at> wrote in message 
news:slrncv8ar0.m68.nick at
> There was a thread about this recently under the title
>  "regular expression: perl ==> python"
> Here is a different solution...
> class Result:
>    def set(self, value):
>        self.value = value
>        return value
> m = Result()
> if m.set('add (\d+) (\d+)', line)):
>    do_add(,
> elif m.set('mult (\d+) (\d+)', line)):
>    do_mult(,
> elif m.set('help (\w+)', line)):
>    show_help(
> -- 
> Nick Craig-Wood <nick at> -- 

More information about the Python-list mailing list