Possible to insert variables into regular expressions?

Craig Ringer craig at postnewspapers.com.au
Fri Dec 10 08:40:32 CET 2004


On Fri, 2004-12-10 at 05:51, Chris Lasher wrote:
> Thanks for the reply, Steve! That ought to work quite nicely! For some
> reason, I hadn't thought of using %-formatting. I probably should have,
> but I'm still learning Python and re-learning programming in general.
> This helps a lot, so thanks again.

Just be careful, when doing this, that your inserted text is also a
regular expression part. You don't want to do this:

re.compile(r'%s made (\d{1,4}.\d{2})' % "J. Smith"

because you'll match "JB Smith made 24.21" etc as well. You could also
end up inserting ?s , *s etc, resulting in some rather frustrating bugs.

--
Craig Ringer




More information about the Python-list mailing list