help learning "re"
Pete J Shinners
pete at visionart.com
Wed Apr 19 22:41:30 EDT 2000
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.
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)
dstfile.write(line)
-----------------------------------------------
surely this can be done correctly, but how?
More information about the Python-list
mailing list