删除括号替换第一场比赛

时间:2017-07-24 21:23:03

标签: python

例如:

string = '(hello) advanced technologies (2015)'

我想删除(你好)但保留(2015)。 我在网上搜索了一下:

 newstring =  re.sub(r'\((?:[^)(]|\([^)(]*\))*\)',"",string)

但它删除了两个括号:

  advanced technologies

如何更改re语句以仅删除第一个括号?

3 个答案:

答案 0 :(得分:6)

如果您真的只想删除第一个匹配项,可以将count参数传递给sub

re.sub(r'\((?:[^)(]|\([^)(]*\))*\)', '', string, count=1)

结果:

' advanced technologies (2015)'

如果你真的想要一些更加花哨的东西,比如在括号之间保持所有年份,请在你的问题中注明。

答案 1 :(得分:2)

re.sub()有一个count参数,用于匹配字母数字使用\w

import re
string = '(hello) advanced technologies (2015)'
newstring =  re.sub(r'\(\w+\)', "", string, 1)
print(newstring)
# advanced technologies (2015)

答案 2 :(得分:1)

除了count=1个答案(一切都很好)之外,如果您知道它始终位于字符串的开头,您可以选择第一个组:

assert re.sub(r'^\([^)]*\)', '', '(a)(b)') == '(b)'

如果它几乎在开始时就可能有类似的东西,例如:是允许的空格。