问题
I have this content:
Data1
import filename.in
Data2
and want to replace import filename.in
line with the content of filename
file, so I use this:
content = re.sub(r'import\s+(.*)\s+\n', '\n' + read_file('\1') + '\n', content)
read_file(in)
returns the content of file in
.
def read_file(file):
with open(file) as f:
return f.read()
the problem is that back-ref \1
does not eval to filename.in
:
No such file or directory: '\\1'
any suggestion?
回答1:
read_file(..)
is called not by the re.sub
. '\1'
is used literally as a filename. In addition to that, \1
is interpreted \x01
.
To do that you need to pass a replacement function instead:
content = re.sub(
r'import\s+(.*)\s+\n',
lambda m: '\n' + read_file(m.group(1)) + '\n', # `m` is a match object
content)
来源:https://stackoverflow.com/questions/24720529/python-pass-regex-back-reference-value-to-method