Search code examples
pythonpython-3.xregexregex-lookaroundsregex-group

Python Regex remove space b/w a Bracket and Number


Python, I have a string like this, Input:

IBNR    13,123   1,234  ( 556 )   ( 2,355 )  934 

Required output- :

Either remove the space b/w the bracket and number

IBNR    13,123   1,234  (556)   (2,355)  934  

OR Remove the brackets:

IBNR   13,123   1,234  556  2,355  934  

I have tried this:

re.sub('(?<=\d)+ (?=\\))','',text1)

This solves for right hand side, need help with left side.


Solution

  • You could use

    import re
    
    data = """IBNR    13,123   1,234  ( 556 )   ( 2,355 )  934 """
    
    def replacer(m):
        return f"({m.group(1).strip()})"
    
    data = re.sub(r'\(([^()]+)\)', replacer, data)
    print(data)
    # IBNR    13,123   1,234  (556)   (2,355)  934 
    

    Or remove the parentheses altogether:

    data = re.sub(r'[()]+', '', data)
    # IBNR    13,123   1,234   556     2,355   934 
    

    As @JvdV points out, you might better use

    re.sub(r'\(\s*(\S+)\s*\)', r'\1', data)