Python Regex remove space b/w a Bracket and Number

Viewed 86

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.

3 Answers

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)

Escape the brackets with this pattern:

(\w+\s+\d+,\d+\s+\d+,\d+\s+)\((\s+\d+\s+)\)(\s+)\((\s+\d+,\d+\s)\)(\s+\d+)

See the results, including substitutions:

https://regex101.com/r/ch6Jge/1

I rarely use the lookahead at all, but I think it does what you want.

re.sub(r'\(\s(\d+(?:\,\d+)*)\s\)', r'\1', text1)
Related