Search code examples
pythonpython-3.xregexstringregexp-replace

Replace ")" by ") " if the parenthesis is followed by a letter or a number using regex


import re

input_text = "((PL_ADVB)dentro ). ((PL_ADVB)ñu)((PL_ADVB)    9u)"

input_text = re.sub(r"\s*\)", ")", input_text)
print(repr(input_text))

How do I make if the closing parenthesis ) is in front of a letter (uppercase or lowercase) it converts the ) to ), so that the following output can be obtained using this code...

"((PL_ADVB) dentro). ((PL_ADVB) ñu)((PL_ADVB) 9u)"

Solution

  • Perform consecutive substitutions (including stripping extra spaces through all the string):

    input_text = "((PL_ADVB)dentro ). ((PL_ADVB)ñu)((PL_ADVB)    9u)"
    
    input_text = re.sub(r"\s*\)", ")", input_text)
    input_text = re.sub(r"\s{2,}", " ", input_text)  # strip extra spaces
    input_text = re.sub(r"\)(?=[^_\W])", ") ", input_text)
    print(repr(input_text))
    

    '((PL_ADVB) dentro). ((PL_ADVB) ñu)((PL_ADVB) 9u)'