RE: Possible to insert variables into regular expressions?

Discussion in 'Python' started by Robert Brewer, Dec 9, 2004.

  1. 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
    MIS
    Amor Ministries
     
    Robert Brewer, Dec 9, 2004
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Jay Douglas
    Replies:
    0
    Views:
    610
    Jay Douglas
    Aug 15, 2003
  2. Pekka Niiranen
    Replies:
    1
    Views:
    330
    Alex Martelli
    Nov 6, 2004
  3. Chris Lasher
    Replies:
    6
    Views:
    1,098
    Steven Bethard
    Dec 10, 2004
  4. ProvoWallis
    Replies:
    0
    Views:
    334
    ProvoWallis
    Jan 19, 2006
  5. Noman Shapiro
    Replies:
    0
    Views:
    235
    Noman Shapiro
    Jul 17, 2013
Loading...

Share This Page