Python 正则表达式删除 space b/w 括号和数字

Python Regex remove space b/w a Bracket and Number

Python,我有这样一个字符串,输入:

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

所需输出- :

要么去掉spaceb/w括号和数字

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

或删除括号:

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

我试过这个:

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

这解决了右侧问题,左侧问题需要帮助。

你可以使用

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 

或者完全删除括号:

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

正如 @JvdV 指出的那样,您最好使用

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

用这种模式转义括号:

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

查看结果,包括替换:

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

我很少使用前瞻,但我认为它可以满足您的需求。

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