Trivial string substitution/parser

Graham Breed x31equsenet at gmail.com
Mon Jun 18 01:58:30 EDT 2007


Samuel wote:

> Thanks, however, turns out my specification of the problem was
> incomplete: In addition, the variable names are not known at compilation
> time.
> I just did it that way, this looks fairly easy already:
>
> -------------------
>     import re
>
>     def variable_sub_cb(match):
>         prepend = match.group(1)
>         varname = match.group(2)
>         value   = get_variable(varname)
>         return prepend + value
>
>     string_re = re.compile(r'(^|[^\\])\$([a-z][\w_]+\b)', re.I)
>
>     input  = r'In this string $variable1 is substituted,'
>     input += 'while \$variable2 is not.'
>
>     print string_re.sub(variable_sub_cb, input)
> -------------------

It gets easier:

    import re

    def variable_sub_cb(match):
        return get_variable(match.group(1))

    string_re = re.compile(r'(?<!\\)\$([A-Za-z]\w+)')

    def get_variable(varname):
        return globals()[varname]

    variable1 = 'variable 1'

    input  = r'In this string $variable1 is substituted,'
    input += 'while \$variable2 is not.'

    print string_re.sub(variable_sub_cb, input)

or even

    import re

    def variable_sub_cb(match):
        return globals()[match.group(1)]

    variable1 = 'variable 1'
    input  = (r'In this string $variable1 is substituted,'
        'while \$variable2 is not.')

    print re.sub(r'(?<!\\)\$([A-Za-z]\w+)', variable_sub_cb, input)


Graham




More information about the Python-list mailing list