python - python中的正则表达式删除太多

标签 python c++ regex

我正在尝试在 Linux 上编译过于干净的 C++ 文件。具体来说,我试图用 python 脚本(我必须使用 python)在 #include 语句中将反斜杠“\”替换为斜杠“/”。 不幸的是,脚本删除了除了最后一个括号之外的几乎所有内容:

}

我正在使用这个脚本:

import os
import re
for dirpath, dirnames, filenames in os.walk(".\Source", topdown=True):
    for file in filenames:
        file = os.path.join(dirpath, file)
        tempfile = file + ".bak"
        with open(tempfile, "w") as target:
            with open(file) as source:
                for line in source:
                    if "#include" in line:
                        re.sub("\\\\", "/", line)
                target.write(line)
        os.remove(file)
        os.rename(tempfile, file)

编辑: 在实现 Simon Fraser 的建议后,脚本现在运行良好。它看起来像这样:

import os
import re
for dirpath, dirnames, filenames in os.walk(".\Source", topdown=True):
    for file in filenames:
        file = os.path.join(dirpath, file)
        tempfile = file + ".bak"
        with open(tempfile, "w") as target:
            with open(file) as source:
                for line in source:
                    if "#include" in line:
                        line = re.sub(r"\\", "/", line)
                    target.write(line)
        os.remove(file)
        os.rename(tempfile, file)

最佳答案

考虑这个部分:

for line in source:
    if "#include" in line:
        re.sub("\\\\", "/", line)
target.write(line)

for 循环中,没有任何内容写入文件 target。一旦 for 循环结束,line 的最后一个值被写出,这可能就是为什么你只得到最后一个 的原因输出。

如果您将 target.write 移动到 for 循环中,事情应该会起作用。 re.sub返回 新值而不是替换 line,因此您也需要在那里进行变量赋值。

for line in source:
    if "#include" in line:
        line = re.sub("\\\\", "/", line)
    target.write(line)

字符串也有一个.replace方法,可能会更快:

for line in source:
    if '#include' in line:
        line = line.replace('\\','/')
    target.write(line)

关于python - python中的正则表达式删除太多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45346047/

相关文章:

python - 检测鼠标是否越过一行python

python - 为什么 subprocess.Popen 的输出与预期的不一样?

c++ - 如何在导入另一个库的库中修复 "invalid use of non-static member function"

c++ - C++ 代码片段的大 O 表示法和时间复杂度

php - 正则表达式匹配任何 UTF 字符,不包括标点符号

python - 我必须将 test_*.py 文件放在 Django 中的哪里?

换行符后带有三个点的 python 字符串...这是什么东西?

c++ - 动态调度在类外部声明的方法

正则表达式:捕获整个组内容

regex - Selenium :是否可以在 Selenium 定位器中使用正则表达式