Regex Error Handling?!

Eladio Ventura eladioventura at hotmail.com
Sun Jan 5 09:26:22 EST 2003


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* 

Any ideas? I probably need a "next if" statement or something, but I'm
new to Python, so...

Here is a sample list to play with:
-----------------------------------
### a list of cool mailing lists###
subscribe mutt-users
subscribe c-prog

subscribe pgsql-general
subscribe vim
subscribe mysql

#subscribe gnu-screen
subscribe unicode

#subscribe Gnu-Screen
#subscribe help-gnu-emacs
subscribe python-list
subscribe zsh-users  
------------------------------------

And here my own pathetic attempt to illustrate the problem:

def regex(lines, part):
	"""Compile regex, return list of matches"""
	# problemo: none-matches: NoneType
	import re
	matches = []
	mismatch = "<type 'NoneType'>"
	regex = re.compile('(\w+)\s+(.*)')

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

def show_active_lists():
	"""list mailbox regex subscribe"""	
	file = open("samplelist", "r")
	lines = file.read().splitlines()
	matches = regex(lines, 2)
	for match in matches: 
		print match

if __name__ == "__main__" :
	show_active_lists() 
-- 
"Thinking gives you wrinkles!"
Malibu Stacy, the Simpsons





More information about the Python-list mailing list