The method using regular expressions is used here. The key point is that when it finds a match, it first modifies the replacement string to match the wrapper of the matched string. This works because re.sub can accept a function instead of a replacement instead of a string.
import re def case_sensitive_replace(s, before, after): regex = re.compile(re.escape(before), re.I) return regex.sub(lambda x: ''.join(d.upper() if c.isupper() else d.lower() for c,d in zip(x.group(), after)), s) test = ''' abc -> def Abc -> Def aBc -> dEf abC -> deF ''' result = case_sensitive_replace(a, 'abc', 'def') print(result)
Result:
def -> def
Def -> Def
dEf -> dEf
deF -> deF
Mark byers
source share