Substituting variables in string with re

Gerrit Holl gerrit at nl.linux.org
Wed Mar 1 12:03:25 CET 2000


<quote name="Kalle A. Pahajoki" date="951903966" email="pahajoki at voimax.cygnnet.jkl.fi">
> As this is my first post on this group, I would like to greet everyone.
> I've found this group/mailing list? to be both very useful and extremely
> entertaining. 

It's both a group (c.l.py) and a mailing list (see .sig of every list
message).

> So far, my encounter with Python and it's fabulous standard library has
> been delightful. However, working on my second Python project, I ran into
> a design problem.
> 
> Below is a (sligthly edited (it worked, all errors are due editing)) part
> of my code that substitutes variables (defined as ${variable}) in a string
> with a value from a dictionary:
> 
> <-- python code begins -->
> # ${<variable>} with group 1 = <variable>
> var_re=re.compile(r'\${([^}]+)}')
> 
> def getgroups(re,str):
>     n=s=0
>     g=[]
>     while 1:
>         m=re.search(str[n:])
> 	if not m:
>             return g
> 	# Kludge kludge (re.search() end up returning the last occurance)
> 	# forever)
> 	if m.group(1) in g:
> 	    break
> 	g.append(m.group(1))
>         # Is it even "legal" to mess around with m's members
> 	(s,n)=m.regs[1]
>     return g
> 
> # subvar=substitute variable
> def subvar(str):
>     group=getgroups(var_re,str)
>     # replace the ${<variable>} with <variable> so we can
>     # later replace it directly
>     str=var_re.sub(r'\1',str)
>     for i in group:
>        # just (while posting) occured to me: if variable names are
>        # common words, this will cause me trouble
>        str=replace(str,i,vardict[i])
>     return str
> 
> <-- python code ends -->
> 
> The above code is, of course, a horrible kludge. Is there a common way to do
> this? What would be a more clean way of doing this? 
</quote>

os.path.expandvars does what you want for environment variables.
It uses the os.environ dictionairy; use the code and modify/generalize
it for your needs.

<function name="expandvars" module="os.path">
# Expand paths containing shell variable substitutions.
# This expands the forms $variable and ${variable} only.
# Non-existant variables are left unchanged.

_varprog = None

def expandvars(path):
    """Expand shell variables of form $var and ${var}.  Unknown variables
are left unchanged"""
    global _varprog
    if '$' not in path:
        return path
    if not _varprog:
        import re
        _varprog = re.compile(r'\$(\w+|\{[^}]*\})')
    i = 0
    while 1:
        m = _varprog.search(path, i)
        if not m:
            break
        i, j = m.span(0)
        name = m.group(1)
        if name[:1] == '{' and name[-1:] == '}':
            name = name[1:-1]
        if os.environ.has_key(name):
            tail = path[j:]
            path = path[:i] + os.environ[name]
            i = len(path)
            path = path + tail
        else:
            i = j
    return path
</function>

regards,
Gerrit.

-- 
-----BEGIN GEEK CODE BLOCK----- http://www.geekcode.com
Version: 3.12
GCS dpu s-:-- a14 C++++>$ UL++ P--- L+++ E--- W++ N o? K? w--- !O !M !V PS+ PE?
Y? PGP-- t- 5? X? R- tv- b+(++) DI D+ G++ !e !r !y
-----END GEEK CODE BLOCK-----




More information about the Python-list mailing list