python - 不确定如何构建以下正则表达式

时间:2016-04-10 01:25:28

标签: python regex

我想替换

'this is my string (anything within brackets)'

'this is my string '

具体样本将是:

'Blue Wire Connectors (35-Pack)'

应替换为

'Blue Wire Connectors '

任何人都可以建议如何在python中构建这个正则表达式吗?

2 个答案:

答案 0 :(得分:1)

要替换的模式应该类似于:r'\(.*?\)'非贪婪地匹配括号中的表达式,以避免将多个括号中的表达式匹配为一个(Python docs):

import re

s = 'this (more brackets) is my string (anything within brackets)'
x = re.sub(r'\(.*?\)', '', s)
# x: 'this  is my string '

但请注意,嵌套括号' this(is(nested))'是正则表达式无法正确处理的规范示例。

答案 1 :(得分:0)

只需使用(\([^)]*\))进行搜索,然后使用empty string ""替换。

此正则表达式捕获( )内的所有内容,直到达到),即括号结束。

Regex101 Demo