简体   繁体   English

python:将正则表达式反向引用值传递给方法

[英]python : pass regex back-reference value to method

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:并想用import filename.in filename文件的内容替换import filename.in行,所以我使用这个:

content = re.sub(r'import\s+(.*)\s+\n', '\n' + read_file('\1') + '\n', content)

read_file(in) returns the content of file in . read_file(in)返回文件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 :问题是 back-ref \\1不会对filename.in求值:

No such file or directory: '\\1'

any suggestion?有什么建议吗?

read_file(..) is called not by the re.sub . read_file(..)不是由re.sub调用的。 '\\1' is used literally as a filename. '\\1'字面上用作文件名。 In addition to that, \\1 is interpreted \\x01 .除此之外, \\1被解释为\\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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM