在循环之前编译 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
。有什么方法可以在进入循环之前编译替换?
我有一些简单的代码可以使用 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
。有什么方法可以在进入循环之前编译替换?