需要剪切字符串

时间:2016-08-25 15:32:02

标签: python regex

我在python 2.7中有一个字符串:

a = 'This is some text ( - 1) - And some more text (0:0) - Some more Text'

我想使用正则表达式获取' - 1'超出这个字符串。

我已经尝试但无法找到它,感谢您的帮助,我已尝试过:

re.search(r'.*?\((.*)\).*', a)

但那并没有奏效。请注意,字符串中有第二个(),但我只需要第一个。

谢谢!

5 个答案:

答案 0 :(得分:1)

默认情况下,正则表达式是贪婪的。您的表达式会获得前一个(

的第一个) 你这样做了:

re.search(r'.*?\((.*)\).*', a)

相反,请使用

re.search(r'.*?\((.*?)\).*', a)

请注意匹配.*?的非贪婪版本(我刚刚为您的正则表达式添加了问号以使其正常工作)

变体:避免在群组捕获中关闭括号

re.search(r'.*?\(([^)]*)\).*', a)

答案 1 :(得分:0)

这样就可以了:

out = re.match('.*?\((.*?)\)', a).groups()[0]

如果您想从原始字符串中删除

a.replace(out, '')

答案 2 :(得分:0)

下面的代码将返回字符串中的所有匹配项:

>>> import re
>>> mystring = 'This is some text ( - 1) - And some more text (0:0) - Some more Text'
>>> regex = re.compile(".*?\((.*?)\)")
>>> result = re.findall(regex, mystring)
>>> result
[' - 1', '0:0']

要获得第一个(或任何您想要的值),请通过相应的索引访问它:

>>> result[0]
'-1'

答案 3 :(得分:0)

您可以使用re.sub替换字符串中找到的第一个匹配项,方法是使用可选的count参数。

>>>a = 'This is some text ( - 1) - And some more text (0:0) - Some more Text'
>>>re.sub(r'\(.+?\)','',a,count=1)

答案 4 :(得分:-1)

怎么样:

tmp_1 = str.split('(', mystring  )
tmp_2 = str.split(')', tmp[1])
result = tmp[0]

此过程更简单,如果括号嵌套,则可以推广。