python:将正则表达式反向引用值传递给方法 [英] python : pass regex back-reference value to method

查看:56
本文介绍了python:将正则表达式反向引用值传递给方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个内容:

Data1
import filename.in
Data2

并且想用 filename 文件的内容替换 import filename.in 行,所以我使用这个:

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) 返回文件 in 的内容.

read_file(in) returns the content of file in.

def read_file(file):
    with open(file) as f:
        return f.read()

问题是 back-ref \1 不会对 filename.in 求值:

the problem is that back-ref \1 does not eval to filename.in :

No such file or directory: '\\1'

有什么建议吗?

推荐答案

read_file(..) 不是由 re.sub 调用的.'\1' 字面上用作文件名.除此之外,\1 被解释为 \x01.

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)

这篇关于python:将正则表达式反向引用值传递给方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆