Possible to insert variables into regular expressions?

Robert Brewer fumanchu at amor.org
Thu Dec 9 23:10:34 CET 2004

Chris Lasher wrote:
> I would like to create a set of very similar regular expression. In
> my initial thought, I'd hoped to create a regular expression with a
> variable inside of it that I could simply pass a string into by
> defining this variable elsewhere in my module/function/class where I
> compile the regular expression, thus making for an easy 
> substitution.

And Steven Bethard replied:
> Can you use the %-formatting operations?  This is what I normally do 
> with a situation like this.  It means you have to compile a 
> new regular expression for each different value you substitute
> into the expression, but that's to be expected anyway when you're
> trying to check several different regular expressions...
>  >>> import re
>  >>> expr = r'(\w*%s\w*)'
>  >>> re.compile(expr % r'oo').findall(s)
> ['Wood', 'Looking']
>  >>> re.compile(expr % r'ou').findall(s)
> ['You', 'Yourself', 'Through', 'You', 'Your']

Just make sure you use re.escape, in case your interpolated string has
regex-sensitive chars.

re.compile(expr % re.escape(r'oo')).findall(s)

Robert Brewer
Amor Ministries
fumanchu at amor.org

More information about the Python-list mailing list