如何使用正则表达式查找字符串中的重复字符

2024-10-02 02:33:50 发布

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

我有任务

"Turn character that is single into '(' and character that are repeated into ')'

for Example "TAAreTheBest" into ")))())()()()"

从上面看,转为“)”的字符是T,A,E

So key is I want to use REGEX to find out which characters is repeated and replace it with ')'

这些都是我以前尝试过的代码,但对我不起作用

(\w)\1* 
([a-zA-Z])\1*
\w{2,}

我对python很陌生。我想了解更多关于正则表达式的知识,所以我认为这个任务可以使用正则表达式来解决它。所以请帮帮我。非常感谢。在


Tags: andtoforsothatisexample字符
1条回答
网友
1楼 · 发布于 2024-10-02 02:33:50

我希望这不是从一开始就做的sub

import re

string = 'baTAAreTheBestaaaaabbbbaaaaaaa'

#1 replace chars that occur more then twice
tmp = ''
while tmp != string:
  tmp = string
  string = re.sub(r'(\w)(((.*)\1){2,})', r')\2', tmp)

#2 replace consecutive pairs (dunno why this are not handled by 3rd replace)
string = re.sub(r'(\w)\1', r'))', string)
#3 replace separate pairs
string = re.sub(r'(\w)(.*)\1', r')\2)', string)
#3 replace unique chars
string = re.sub(r'\w', '(', string)
print(string)

相关问题 更多 >

    热门问题