best way to do a series of regexp checks with groups
Nick Craig-Wood
nick at craig-wood.com
Mon Jan 24 01:46:18 EST 2005
Mark Fanty <markfanty at yahoo.com> 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(re.search(r'add (\d+) (\d+)', line)):
do_add(m.value.group(1), m.value.group(2))
elif m.set(re.search(r'mult (\d+) (\d+)', line)):
do_mult(m.value.group(1), m.value.group(2))
elif m.set(re.search(r'help (\w+)', line)):
show_help(m.value.group(1))
--
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick
More information about the Python-list
mailing list