import re texto = "ABC ABC. ABC.png ABC thumb.png" regex = r"ABC(?!.png)|ABC(?! thumb.png)" novo = re.sub(regex, "bueno", texto) print(novo) I'm trying to replace the ABC word with exceptions. I only want to replace it if it doesn't follow the word ".png" or " thumb.png". The string would be then "ABC thumb.png" I expected bueno bueno. ABC.png ABC thumb.png But the output is this bueno bueno. bueno.png bueno thumb.png It isn't detecting the space and it actually messes up the first condition. Continue reading...