4

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.

Jan
  • 42,290
  • 8
  • 54
  • 79
karan
  • 309
  • 2
  • 10

3 Answers3

5

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)
Jan
  • 42,290
  • 8
  • 54
  • 79
  • 1
    Nice, in the second example OP wants to replace paranthesis and spaces. Maybe adapt your second example a little. Possibly something like: `data = re.sub(r'\(\s*|\s*\)', r'', data)` but I bet that can be done better =) – JvdV Jun 09 '20 at 09:10
  • @JvdV: Why not, added your example. – Jan Jun 09 '20 at 09:13
  • Cool, I changed my example, but not sure if the previous was quicker. – JvdV Jun 09 '20 at 09:17
  • @JvdV: Probably yes (haven't tested). An alternation is usually slower. – Jan Jun 09 '20 at 09:19
0

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

Gustav Rasmussen
  • 3,720
  • 4
  • 23
  • 53
0

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)
Detlef
  • 1