Use the following:
> re.sub(r'(.+?)1+', r'1', 'xyzzyxxyzzyxxyzzyx')
'xyzzyx'
> re.sub(r'(.+?)1+', r'1', 'abcbaccbaabcbaccbaabcbaccba')
'abcbaccba'
> re.sub(r'(.+?)1+', r'1', 'iiiiiiiiiiiiiiiiii')
'i'
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.
DEMO.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…