best way to do a series of regexp checks with groups
Mark Fanty
markfanty at yahoo.com
Sun Jan 23 11:05:26 EST 2005
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);
}
or even
do_add($1,$2) if /add (\d+) (\d+)/;
do_mult($1,$2) if /mult (\d+) (\d+)/;
show_help($1) if /help (\w+)/;
How can I best do this in pyhon? Attempt 1:
m = re.search(r'add (\d+) (\d+)', $line)
if m:
do_add(m.group(1), m.group(2))
else:
m = re.search(r'mult (\d+) (\d+)', $line)
if m:
do_mult(m.group(1), m.group(2))
else:
m = re.search(r'help (\w+)', $line)
show_help(m.group(1))
The increasing nesting is a problem. I could put them in a while loop just
so I can use break
while 1:
m = re.search(r'add (\d+) (\d+)', $line)
if m:
do_add(m.group(1), m.group(2))
break
m = re.search(r'mult (\d+) (\d+)', $line)
if m:
do_mult(m.group(1), m.group(2))
break
m = re.search(r'help (\w+)', $line)
if m:
show_help(m.group(1))
break
No nesting, but the while is misleading since I'm not looping and this is a
bit awkward. I don't mind a few more key strokes, but I'd like clarity. I
wish I could do
if m = re.search(r'add (\d+) (\d+)', $line):
do_add(m.group(1), m.group(2))
elif m = re.search(r'mult (\d+) (\d+)', $line):
do_mult(m.group(1), m.group(2))
else m = re.search(r'help (\w+)', $line):
show_help(m.group(1))
Now that's what I'm looking for, but I can't put the assignment in an
expression. Any recommendations? Less "tricky" is better. Not having to
import some personal module with a def to help would be better (e.g. for
sharing)..
Thanks
More information about the Python-list
mailing list