在Python中使用正则表达式删除重复的单词

jac*_*hab 4 python regex

我需要删除字符串中的重复单词,以便'the (the)'成为'the'.为什么我不能这样做?

re.sub('(.+) \(\1\)', '\1', 'the (the)')
Run Code Online (Sandbox Code Playgroud)

谢谢.

jen*_*ram 6

你需要双倍地逃避反向引用:

re.sub('(.+) \(\\1\)', '\\1', 'the (the)')
--> the
Run Code Online (Sandbox Code Playgroud)

或者使用r前缀:

当"R"或"R"的前缀是目前,以下反斜杠一个字符包含不变化的串中,且所有反斜杠留在的字符串中.

re.sub(r'(.+) \(\1\)', r'\1', 'the (the)')
--> the
Run Code Online (Sandbox Code Playgroud)