help learning "re"

Fredrik Lundh effbot at telia.com
Thu Apr 20 10:33:07 CEST 2000


Pete J Shinners <pete at visionart.com> wrote:
> i'm trying to get the hang of these regular expression
>
> i'm trying to write a function that takes two filenames
> and copies one to the other. while it is copying i want
> it to scan for any environment variable names and substitute
> the expanded value.

os.path.expandvars(name)

> sounded like a fabulous time to learn the regexp.
> sadly it doesn't work. the code runs, but none of the
> variables are found or substituted
>
> here's what i expected to work
> ----------------------------------------------
> import os, re
>
>
> def subvar(regfind):
>     "callback for regex substitution"
>     var = regfind.group(0)[1:]
>     print 'REGEX found var:', var #temp debugging. never gets here
>     return os.environ.get(var, '$'+var)
>
>
> def smartcopy(source, dest):
>     "copies files. substites env.variables with values"
>     srcfile = open(source, 'r')
>     dstfile = open(dest, 'w')
>     regexp = re.compile(r"\$[0-9A-Z_]+")
>     while 1:
>         line = srcfile.readline()
>         if not line: break
>         regexp.sub(subvar, line)

regexp.sub returns the new value, it doesn't modify
line in place.

>         dstfile.write(line)
>
> -----------------------------------------------
> surely this can be done correctly, but how?

the only bug I can spot is the regexp.sub return value.  the
expression and the substitution function works just fine for
me...

(try adding "print regexp.sub(subvar, '$HOME')" just after
the re.compile to see what I mean)

</F>





More information about the Python-list mailing list