在Python中使用regex删除重复单词

2024-04-19 04:46:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要删除字符串中的重复单词,这样'the (the)'将变成{}。为什么我不能这样做呢?在

re.sub('(.+) \(\1\)', '\1', 'the (the)')

谢谢。在


Tags: the字符串re单词
2条回答

根据documentation:“原始字符串表示法(r”text“)保持正则表达式正常。”

您需要双重转义反向引用:

re.sub('(.+) \(\\1\)', '\\1', 'the (the)')
 > the

或者使用^{} prefix

When an "r" or "R" prefix is present, a character following a backslash is included in the string without change, and all backslashes are left in the string.

^{pr2}$

相关问题 更多 >