kar*_*ran 4 python regex regex-group python-3.x regex-lookarounds
Python,我有一个这样的字符串,输入:
IBNR 13,123 1,234 ( 556 ) ( 2,355 ) 934
Run Code Online (Sandbox Code Playgroud)
所需的输出-:
要么删除空格 b/w 括号和数字
IBNR 13,123 1,234 (556) (2,355) 934
Run Code Online (Sandbox Code Playgroud)
或删除括号:
IBNR 13,123 1,234 556 2,355 934
Run Code Online (Sandbox Code Playgroud)
我试过这个:
re.sub('(?<=\d)+ (?=\\))','',text1)
Run Code Online (Sandbox Code Playgroud)
这解决了右侧,需要左侧的帮助。
你可以用
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
Run Code Online (Sandbox Code Playgroud)
或者完全删除括号:
data = re.sub(r'[()]+', '', data)
# IBNR 13,123 1,234 556 2,355 934
Run Code Online (Sandbox Code Playgroud)
正如@JvdV指出的那样,您可能更好地使用
re.sub(r'\(\s*(\S+)\s*\)', r'\1', data)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
71 次 |
| 最近记录: |