Search code examples
pythonregexuppercaselowercaserepeat

how do you substitute a repeating character both uppercase and lowercase with regex in python


Say you have a word "Aabrakadaabra" and what you want to do is find the repeating characters and replace them with a single one. which in our case should return "Abrakadabra".

what i did was re.sub(r"([a-zA-z])\1",r"\1","Aabrakadaabra") which returns 'Aabrakadabra' and this regex cannot catch when there is an uppercase and a lowercase repeating. Im not sure if there is an easy, one liner way to do this but any help would be educative.


Solution

  • Use re.IGNORECASE.

    >>> re.sub(r"([a-zA-z])\1",r"\1","Aabrakadaabra", flags=re.IGNORECASE)
    'Abrakadabra'