Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/actionscript-3/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用正则表达式查找字符串中的重复字符_Python_Regex_Python 3.x - Fatal编程技术网

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

Python 如何使用正则表达式查找字符串中的重复字符,python,regex,python-3.x,Python,Regex,Python 3.x,我有一个任务 将单个字符转换为“(”和 重复成“')” 例如“TAAreTheBest”变成了“)))())()” 从上面看,转向“')的字符是T、A、E 所以关键是我想使用正则表达式来找出哪些字符是重复的,并将其替换为“')” 这些是我以前尝试过的代码,对我来说不起作用 (\w)\1* ([a-zA-Z])\1* \w{2,} 我对python非常陌生。我想了解更多关于REGEX的知识,所以我认为这个任务可以使用REGEX来解决。所以请帮助我。谢谢。我希望这不是从一个子完成的 import

我有一个任务

将单个字符转换为“(”和 重复成“')”

例如“TAAreTheBest”变成了“)))())()”

从上面看,转向“')的字符是T、A、E

所以关键是我想使用正则表达式来找出哪些字符是重复的,并将其替换为“')”

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

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

我对python非常陌生。我想了解更多关于REGEX的知识,所以我认为这个任务可以使用REGEX来解决。所以请帮助我。谢谢。

我希望这不是从一个子
完成的

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)