How best to write this if-else?
Tim Peters
tim.one at home.com
Sat Apr 21 16:41:32 EDT 2001
[Roy Smith]
> I want to test a line to see if it matches any of a bunch of pre-
> compile regexes. I also want to capture the match objects. What
> really want to write is something like this (pseudo-code):
>
> e1 = re.compile ('...')
> e2 = re.compile ('...')
> e3 = re.compile ('...')
>
> line = file.readline()
> if (m = e1.match (line)):
> text = m.group(1)
> elif (m = e2.match (line)):
> text = m.group(1)
> elif (m = e3.match (line)):
> text = m.group(1)
> ...
Na, you really want something like this:
regexps = [re.compile('...'),
re.compile('...'),
...
re.compile('...')]
line = file.readline()
for r in regexps:
match = r.match(line)
if match:
break
# Now, assuming regexps isn't an empty list, match is None if and only
# if no regexp matched.
if match:
text = match.group(1)
else:
text = "There's a lobster on the loose!"
Now when your set of regexps changes, you need only fiddle the regexps list;
no need to touch the *code* ever again. If you do this a lot, write a little
class that takes a list of regexps in the constructor, and give it a (say)
.find_first_match(line) method.
iteration-beats-embedded-assignments-by-a-long-shot-ly y'rs - tim
More information about the Python-list
mailing list