Using dictionary to hold regex patterns?

Terry Reedy tjreedy at udel.edu
Sun Nov 23 13:36:01 EST 2008


Gilles Ganault wrote:
> Hello
> 
> After downloading a web page, I need to search for several patterns,
> and if found, extract information and put them into a database.
> 
> To avoid a bunch of "if m", I figured maybe I could use a dictionary
> to hold the patterns, and loop through it:

Good idea.

import re

> pattern = {}
> pattern["pattern1"] = ">.+?</td>.+?>(.+?)</td>"

... = re.compile("...")

> for key,value in pattern.items():

for name, regex in ...

> 	response = ">whatever</td>.+?>Blababla</td>"
> 
> 	#AttributeError: 'str' object has no attribute 'search'

Correct, only compiled re patterns have search, better naming would make 
error obvious.

> 	m = key.search(response)

m = regex.search(response)

> 	if m:
> 		print key + "#" + value

print name + '#' + regex




More information about the Python-list mailing list