iterate lines with regex
MRAB
python at mrabarnett.plus.com
Mon Aug 3 13:29:56 EDT 2009
Robert Kern wrote:
[snip]
>
> 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
>
re.search and re.match will return a MatchObject if successful or None
if unsuccessful. A MatchObject is always true, so you can simplify to:
...
if key_match:
this_key = key_match.group(1)
# ... do something with this_key
...
More information about the Python-list
mailing list