Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python re.sub() is not replacing every match

I'm using Python 3 and I have two strings: abbcabb and abca. I want to remove every double occurrence of a single character. For example:

abbcabb should give c and abca should give bc.

I've tried the following regex (here):

(.)(.*?)\1

But, it gives wrong output for first string. Also, when I tried another one (here):

(.)(.*?)*?\1

But, this one again gives wrong output. What's going wrong here?


The python code is a print statement:

print(re.sub(r'(.)(.*?)\1', '\g<2>', s)) # s is the string
like image 296
vrintle Avatar asked Aug 26 '26 00:08

vrintle


2 Answers

It can be solved without regular expression, like below

>>>''.join([i for i in s1 if s1.count(i) == 1])
'bc'
>>>''.join([i for i in s if s.count(i) == 1])
'c'
like image 166
JON Avatar answered Aug 27 '26 16:08

JON


re.sub() doesn't perform overlapping replacements. After it replaces the first match, it starts looking after the end of the match. So when you perform the replacement on

abbcabb

it first replaces abbca with bbc. Then it replaces bb with an empty string. It doesn't go back and look for another match in bbc.

If you want that, you need to write your own loop.

while True:
    newS = re.sub(r'(.)(.*?)\1', r'\g<2>', s)
    if newS == s:
        break
    s = newS
print(newS)

DEMO

like image 45
Barmar Avatar answered Aug 27 '26 16:08

Barmar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!