Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing all overlapping patterns in a string

Given the string: s = "101010101", I would like to replace every occurrence of the pattern 010, with the pattern 0X0, so that the result should be s = "10X0X0X01".

Another similar problem is to replace the same pattern 010 with 00, so that the resulting string should be s = 100001.

So far, I tried by:

import re
s = "101010101"
s = re.sub("010", "0X0", s)

but the resulting string is 10X010X01, missing to replace the 1 in the middle.

Any help?

like image 542
sono Avatar asked Feb 07 '26 08:02

sono


1 Answers

You can use lookarounds to find values without including them in the match:

s = re.sub(r"(?<=0)1(?=0)", "X", s)

(?<=0)1(?=0) matches a single 1 character that is preceded – (?<=…) – and followed – (?=…) – by a zero.

like image 78
Ry- Avatar answered Feb 09 '26 11:02

Ry-



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!