在循环之前编译 Python 的 re.sub 的替换

Compile replacement for Python's re.sub before the loop

我有一些简单的代码可以使用 Python 的 re 来替换子字符串:

pattern = re.compile(r'(--type-header )([^ ]*)')
for x in somelist:
    filename = '...'  # here is a filename
    switches = x.replace('alice', 'bob')  # simple string
    switches = pattern.sub(
        r'' + f'{os.path.dirname(filename)}/' + r'',
        switches
    )

我要替换的子串:

--type-header cond_enum_04.h

在 Linux/macOs 上一切都像魅力一样。但是在 Windows 我得到:

re.error: bad escape \c at position 16

大约250次循环迭代(249次迭代成功)。我怀疑这是 Windows 下循环中的一个显着特征 re。有什么方法可以在进入循环之前编译替换?

问题是由于 Windows 上的目录分隔符被解释为转义字符(参见 here)。

一种可能的解决方案是使用 pathlib 来处理路径,并调用其 .as_posix 方法以在各种平台上以一致的格式呈现路径字符串,然后适用于应用正则表达式.

所以在这种情况下,替换为:

f'{os.path.dirname(filename)}/'

像这样:

f'{Path(filename).parent.as_posix()}/'