正则表达式删除字符串中的重复字符模式 [英] Regex to remove repeated character pattern in a string

查看:63
本文介绍了正则表达式删除字符串中的重复字符模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可能有重复字符模式的字符串,例如

I have a string that may have a repeated character pattern, e.g.

'xyzzyxxyzzyxxyzzyx'

我需要编写一个正则表达式,用最小的重复模式替换这样的字符串:

I need to write a regex that would replace such string with its smallest repeated pattern:

'xyzzyxxyzzyxxyzzyx' becomes 'xyzzyx',

'abcbaccbaabcbaccbaabcbaccba' becomes 'abcbaccba'

推荐答案

使用以下内容:

> re.sub(r'(.+?)\1+', r'\1', 'xyzzyxxyzzyxxyzzyx')
'xyzzyx'
> re.sub(r'(.+?)\1+', r'\1', 'abcbaccbaabcbaccbaabcbaccba')
'abcbaccba'
> re.sub(r'(.+?)\1+', r'\1', 'iiiiiiiiiiiiiiiiii')
'i'

它基本上匹配重复自身的模式(.+?)\1+,并删除除重复模式之外的所有内容,该模式在第一组\1.还要注意,在这里使用不情愿的限定符,即 +? 会使正则表达式回溯很多.

It basically matches a pattern that repeats itself (.+?)\1+, and removes everything but the repeating pattern, which is captured in the first group \1. Also note that using a reluctant qualifier here, i.e., +? will make the regex backtrack quite a lot.

演示.

这篇关于正则表达式删除字符串中的重复字符模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆