Regular expression question

John Hunter jdhunter at ace.bsd.uchicago.edu
Sun Nov 24 11:19:20 EST 2002


>>>>> "Jonah" == Jonah  <jonah13579 at hotmail.com> writes:

    Jonah> Thanks for the well-thought out response.  I was wondering
    Jonah> whether a function map would be necessary.  I know that in
    Jonah> a production environment, the line I use gives the user too
    Jonah> much power, but I use this for my own purposes, and I
    Jonah> control the source and the script.  As for thinking in
    Jonah> python, I'm still at the very earliest stages of looking at
    Jonah> python (and ruby for that matter) as a possible replacement
    Jonah> for/addition to perl.

You can forgo the function map and instead use a single function
'process' as a dispatcher, to lower case WHATEVER and eval a call to
the lowered string

import re

def whatever(v):
    return 'WhAtEvEr' + v

def want(v):
    return 'WaNt' + v
    
def process(m):
    variable = '!'  # your $variable
    return eval(m.group(1).lower() + '(variable)')

print re.sub('%%(.*?)%%', process, 'I will do %%WHATEVER%% you %%WANT%%')

The extra overhead is much lower.  It has the downside of using the
eval, but you seem aware of these risks.

With thought, this could probably be converted into a one liner as in
perl, but that is not usually an instinct around here, except for
didactic purposes of course.

John Hunter




More information about the Python-list mailing list