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

2024-10-01 00:17:02 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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..

现在从这段文字我想得到三个字符串

  1. (English: (The) (Sc)oundrels()hggg)
  2. (sa)
  3. (roles)

为此,我尝试了遵循正则表达式

re.compile(r'\(.*?\)')

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


Tags: andofthe字符串reenglishwithsa
1条回答
网友
1楼 · 发布于 2024-10-01 00:17:02

这将匹配深度为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)']

相关问题 更多 >