Regex Error Handling?!

Fredrik Lundh fredrik at pythonware.com
Sun Jan 5 10:39:56 EST 2003


Eladio Ventura wrote:

> I have a list of various mailing lists of interest which I want to
> process via a regex. Unfortunately the app crashes as soon as it gets
> to a line which doesn't match the regex, such as an empty line and the
> like. These are of the type 'NoneType', but I still can't figure out
> how to make it ignore non-matches to create a stable program. *sigh*

re.search returns a match object if the pattern matches, or None
if it doesn't match.  the "if" statement treats match objects as true
values, so you can use "if" right away to check for matches:

for line in lines:
    match = regex.search(line)
    if match:
        matches.append(match.group(part))
    else:
        print "We got a mismatched line!"

</F>






More information about the Python-list mailing list