getfirst and re

Tim Chase python.list at tim.thechases.com
Wed Jan 6 12:27:50 EST 2010


> I need to do something like the following:
> 
>     pat = re.compile('edit[0-9]*:[0-9]*')
>     check = form.getfirst(pat)
> 
> (to check things like 'edit0:1') How do I do this?

Well, you can do it either as

   check = pat.search(string_to_search)

which is pretty plainly detailed in the help for the "re" module, 
both under the search() function and under the "8.2.2 Matching 
vs. Searching" section.

Alternatively, if you plan to get the others too, you can use

   fi = pat.finditer(string_to_search)
   check = fi.next().group(0) # beware this may throw
   # a StopIteration if there are no more matches.

which would usually be done inside a loop where the StopIteration 
does the Right Thing(tm).

But if you're using it on HTML form text, regexps are usually the 
wrong tool, and you should be using an HTML parser (such as 
BeautifulSoup) that knows how to handle odd text and escapings 
better and more robustly than regexps will.

-tkc






More information about the Python-list mailing list