Possible to insert variables into regular expressions?

Terry Hancock hancock at anansispaceworks.com
Fri Dec 10 19:55:22 CET 2004

On Thursday 09 December 2004 03:51 pm, 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.

Remember, in Python, a regex (well, regex source) is just a string, so
you can do any string manipulation you want to with it, and python has
a lot of tools for doing that.

One cool way to make regexes more readable, that i've seen proposed,
is to break them into components like the following (please pardon my
lack of regex skill, these may not actually work , but you get the idea):

normalword  = r'[A-Za-z][a-z]*'
digit           = r'\d'
capletter   = r'[A-Z]'

codeblock = normalword + 4*digit + '-' + 3*digit + 2*capletter + '\s+' + normalword

or somesuch (the 'r' BTW stands for 'raw', not 'regex', and while it's the most
obvious use, there's nothing particularly special about r strings, except for
not trying to process escape characters, thus avoiding the "pile of toothpicks"

And hey, you could probably use a regex to modify a regex, if you were
really twisted. ;-)

Sorry.  I really shouldn't have said that. Somebody's going to do it now. :-P


Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com

More information about the Python-list mailing list