import re
class RepeatReplacer(object):
"""
在该方法中,一个字符指的是正则表达式分组中的先前字符。消除重复字符也被认为是标准化任务之一。
RepeatReplacer类通过编译正则表达式和替换的字符串来工作,并使用 backreference.Repeat_regexp 来定义。
它匹配可能是以零个或多个(\w *)字符开始,以零个或多个(\w *),或者一个(\w)其后面带有相同字符的字符而结束的字符。
"""
def __init__(self):
self.repeat_regexp = re.compile(r'(\w*)(\w)\2(\w*)\3')
self.repl = r'\1\2\3'
# self.repl1=r'\1'
# self.repl2=r'\2'
# self.repl3=r'\3'
def replace(self, word):
repl_word = self.repeat_regexp.sub(self.repl, word)
# repl_word1 = self.repeat_regexp.sub(self.repl1, word)
# repl_word2 = self.repeat_regexp.sub(self.repl2, word)
# repl_word3 = self.repeat_regexp.sub(self.repl3, word)
print('*'*10)
print(repl_word)
# print('1:',repl_word1)
# print('2:',repl_word2)
# print('3:',repl_word3)
if repl_word != word:
return self.replace(repl_word)
else:
return repl_word
replacer = RepeatReplacer()
print(replacer.replace('oohhhh'))
# oh
print(replacer.replace('hottt'))
# hot
高级正则表达式,哪位大佬可以看懂的话,麻烦指点一下
最新推荐文章于 2024-06-06 23:55:54 发布