Possible to insert variables into regular expressions?

Steven Bethard steven.bethard at gmail.com
Thu Dec 9 16:30:56 EST 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.

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
 >>> s = """\
... 1. Drive My Car
... 2. Norwegian Wood (This Bird Has Flown)
... 3. You Won't See Me
... 4. Nowhere Man
... 5. Think for Yourself
... 6. Word
... 7. Michelle
... 8. What Goes On
... 9. Girl
... 10. I'm Looking Through You
... 11. In My Life
... 12. Wait
... 13. If I Needed Someone
... 14. Run for Your Life"""
 >>> 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']

Steve



More information about the Python-list mailing list