best way to do a series of regexp checks with groups

Nick Craig-Wood nick at
Mon Jan 24 07:46:18 CET 2005

Mark Fanty <markfanty at> wrote:
>  In perl, I might do (made up example just to illustrate the point):
>  if(/add (\d+) (\d+)/) {
>    do_add($1, $2);
>  } elsif (/mult (\d+) (\d+)/) {
>    do_mult($1,$2);
>  } elsif(/help (\w+)/) {
>    show_help($1);
>  }

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)):
elif m.set('mult (\d+) (\d+)', line)):
elif m.set('help (\w+)', line)):

Nick Craig-Wood <nick at> --

More information about the Python-list mailing list