Using dictionary to hold regex patterns?

John Machin sjmachin at lexicon.net
Sun Nov 23 15:48:27 EST 2008


On Nov 24, 5:36 am, Terry Reedy <tjre... at udel.edu> wrote:
> 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

Perhaps you meant:
   print key + "#" + regex.pattern



More information about the Python-list mailing list