Search code examples
pythonregexstringuppercaselowercase

Using a regular expression to remove a uppercase letter if it's previous and next letter is lowercase?


I am new in regular expression. I want to remove a uppercase letter if it has lowercase before and after it. If the input is "I wilYl go theXre" then the output should be "I will go there". How can I get it?


Solution

  • You can use a lookaround:

    import re 
    
    s='I wilYl go theXre'
    
    print(re.sub(r'(?<=[a-z])([A-Z])(?=[a-z])','',s))
    #               ^ lookbehind     ^lookahead
    

    Prints:

    I will go there