python : pass regex back-reference value to method

折月煮酒 提交于 2021-02-02 09:31:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!