You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python正则匹配指定代码行并改为注释行的实现求助

Python正则匹配指定代码行并改为注释行的实现求助

看起来你现在的需求是把匹配到的SQL执行行改成注释保留下来,而不是直接删掉,这个其实只需要调整正则替换的目标字符串就可以啦,我来给你一步步说怎么改:

首先,你原来的subst_a是空字符串,现在我们要做的是给整个匹配到的行前面加上# (井号加空格,符合Python注释的规范)。在Python的re.sub里,可以用\g<0>来引用整个正则匹配到的内容,所以只需要把替换字符串改成下面这样:

subst_a = r"# \g<0>"

这样一来,当正则匹配到目标行的时候,就会把该行变成# 原内容的注释形式,而不是直接清空。

另外,我注意到你的replacetext函数是嵌套在if '.py' == file_ext:这个判断里面的,虽然语法上没问题,但从代码可读性和复用性来说,建议把这个函数移到modify_user_code函数的外面,避免每次遍历到py文件都重复定义函数,逻辑会更清晰。

还有个小细节:你的正则里匹配单引号用了[\'a-zA-Z0-9\/_]+,其实可以简化成'[a-zA-Z0-9/_]+'(因为你用的是r前缀的单引号字符串,单引号不需要在字符类里转义),优化后的正则可以写成:

regex_a = r"^[a-zA-Z]+\.sql\(\"create database if not exists [a-zA-Z0-9/_]+ location '[a-zA-Z0-9/_]+'\"\)"

最后,把修改后的部分整合到你的代码里,大概是这样:

def modify_user_code():
    # 优化后的正则,匹配目标行
    regex_a = r"^[a-zA-Z]+\.sql\(\"create database if not exists [a-zA-Z0-9/_]+ location '[a-zA-Z0-9/_]+'\"\)"
    # 替换成带#的注释行
    subst_a = r"# \g<0>"

    dir_list = os.listdir(os.path.join(path_root, "tasks"))

    for file_name in dir_list:
        logger.debug(f"dir has {file_name}")
        file_ext = os.path.splitext(file_name)[1]
        file_edit = os.path.join(path_root, 'tasks', file_name)
        logger.info(f"editing {file_edit}")

        if '.py' == file_ext:
            replacetext([regex_a], [subst_a], file_edit)

# 把replacetext函数移到外部,方便复用
def replacetext(search_text_arr, replace_text_arr, path_to_file):
    with open(path_to_file, 'r+') as f:
        file = f.read()
        for i in range(len(search_text_arr)):
            logger.debug(f"search={search_text_arr[i]} replace={replace_text_arr[i]}")
            file = re.sub(search_text_arr[i], replace_text_arr[i], file, flags=re.MULTILINE)
        f.seek(0)
        size = f.write(file)
        f.truncate()
    return size

这样运行之后,原来匹配到的行就会变成注释行保留在文件里啦,比如原来的foo.sql("create database if not exists test_db location '/data/db'")会变成# foo.sql("create database if not exists test_db location '/data/db'")。

备注:内容来源于stack exchange,提问作者abhishek jain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.22 11:14:39