如何在python中使用正则表达式从括号中获取字符串

时间:2015-02-13 11:52:39

标签: python regex

我想从括号中检索字符串。以下是文字

  

Kaminey (英文:(The)(Sc)oundrels()hggg)   asd (sa) dsad是2009年由印度执导的Caper惊悚片   Vishal Bhardwaj以及Shahid Kapoor,Priyanka Chopra和Amol为特色   Gupte领先(角色)。以孟买为背景   在黑社会中,Kaminey跟随一对双胞胎之间的竞争   在一个单一的过程中,使用口齿不清而另一个口吃   天..

现在从这篇文章中我想得到三个字符串

  
      
  1. (英文:(The)(Sc)oundrels()hggg)
  2.   
  3. (SA)
  4.   
  5. (角色)
  6.   

我曾尝试使用正则表达式

  

re.compile(R '\(。*?\)')

     

re.compile(R '/ \(([^)] +)\)/')

1 个答案:

答案 0 :(得分:1)

这将匹配深度为1的括号。

>>> example = 'My email is John@gmail.com. My name is John. Her email is Anna@gmail.com .I am sam'
>>> s = '''Kaminey (English: (The) (Sc)oundrels()hggg) asd (sa) dsad is a 2009 Indian caper thriller film directed by Vishal Bhardwaj and featuring Shahid Kapoor, Priyanka Chopra and Amol Gupte in the lead (roles). Set against the backdrop of the Mumbai underworld, Kaminey follows a rivalry between a pair of twins, one with a lisp and the other with a stutter, over the course of a single day..'''
>>> import re
>>> re.findall(r'\((?:\([^()]*\)|[^()])*\)', s)
['(English: (The) (Sc)oundrels()hggg)', '(sa)', '(roles)']