iterate lines with regex

Robert Kern robert.kern at gmail.com
Mon Aug 3 12:24:19 EDT 2009


On 2009-08-01 14:39, Michael Savarese wrote:
>
> I'm a python newbie and I'm trying to test several regular expressions
> on the same line before moving on to next line.
> it seems to move on to next line before trying all regular expressions
> which is my goal.
> it only returns true for first regular expression
> does the curser have to be rest to beginning of line? If so, how would I
> do that.
> remember I'm new
> thanks in advance to any advice
> Mike S.
>
> the following is part of my code,
> readThis=open('c:/9320.txt','r')
>
> for line in readThis:
>      try:
>          thisKey = key.search(line).group(1)
>          thisMap = map.search(line).group(1)
>          thisParcel = parcel.search(line).group(1)
>      except:
>          continue

What is happening is that either key or map fails to match and trying to get a 
group raises an exception. This is caught, and the "continue" statement tells 
the for-loop to go to the next line in readThis. The "continue" statement does 
not mean "go back to where the error was raised and continue executing as if no 
error happened".

The key to using try: except: properly is to surround as little code as 
possible. Also, to explicitly state which exceptions you are going to catch.

In this case, though, you don't want to use exceptions. You should deal with the 
match objects that are the result of the .search() method.

for line in readThis:
     key_match = key.search(line)
     if key_match is not None:
         this_key = key_match.group(1)
         # ... do something with this_key
     map_match = map.search(line)
     if map_match is not None:
         this_map = map_match.group(1)
         # ... do something with this_map
     parcel_match = parcel.search(line)
     if parcel_match is not None:
         this_parcel = parcel_match.group(1)
         # ... do something with this_parcel


-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco




More information about the Python-list mailing list