即使您应用其他答案提到的更改(转义元组中的搜索词),这是有效且重要的,您仍然会得到
Traceback (most recent call last):
File "<pyshell#4>", line 6, in <module>
str1 = re.sub(match.group(),"\\"+match.group(),str1)
error: unbalanced parenthesis
但这次在不同的路线上。所以当你使用正则表达式的子函数时,第一个参数需要是一个有效的正则表达式。match.group()可以是任何东西,不一定是平衡的。这是正则表达式令人窒息的地方。因此,我们可以从中获取字符串match.group()并将其转义,因此我们正在搜索文字。从而将线路更改为
str1 = re.sub(re.escape(match.group()),"\\"+match.group(),str1)
另一方面,我们可以只编译一次模式,然后记住它
pattern = re.compile(r"("+i+")")
str1 = re.sub(pattern,"\\"+match.group(),str1)
最终代码是:
str1 = "/path/happy (dog)"
tuple_1 = (r'\s+', r'\(', r'\)')
for i in tuple_1:
pattern = re.compile(r"("+i+")")
match = pattern.search(str1)
if match:
str1 = re.sub(pattern,"\\"+match.group(),str1)
str1 现在是'/path/happy\\ \\(dog\\)'