How best to write this if-else?

Mike C. Fletcher mcfletch at home.com
Sat Apr 21 16:48:05 EDT 2001


Use the first-class nature of regex objects to your advantage, also plan for
eventuality of not finding the value...

mysearchers = [
	re.compile ('...'),
	...
]

text = None
for searcher in mysearchers:
	result = searcher.search( blah )
	if result:
		text = result.group(1)
		break # stop searching

if text is None:
	raise ValueError( '''Unable to find value in given string''', blah)

HTH,
Mike

-----Original Message-----
From: Roy Smith [mailto:roy at panix.com]
Sent: Saturday, April 21, 2001 16:03
To: python-list at python.org
Subject: How best to write this if-else?


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)

but I can't write it that way because python doesn't have assignment
operators.  Seems like I stuck with something like:

m = e1.match(line)
if m:
   text = m.group(1)
else:
   m = e2.match(line)
   if m:
      text = m.group(1)
   else:
     m = e3.match(line)
      if m:
        text = m.group(1)

but the best word I can think to describe that style of coding is "silly".
Is there really no more straight-forward way to do what I want?
--
http://mail.python.org/mailman/listinfo/python-list





More information about the Python-list mailing list