gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 08:54:42 25 4
gpt4 key购买 nike

我有一个任务

"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很陌生。我想了解更多关于 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)

关于python - 如何使用正则表达式查找字符串中的重复字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52858064/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com