Python正则表达式获取所有文本直到(,并获取括号内的文本

4 投票
4 回答
12807 浏览
提问于 2025-04-16 02:27

我需要帮助进行两个正则表达式的操作。

  1. 提取所有文本直到遇到一个左括号。

    比如说,'this is so cool (234)' 变成 'this is so cool'

  2. 提取括号里面的文本,也就是数字 '234'

4 个回答

0

不需要使用正则表达式。

>>> s="this is so cool (234)"
>>> s.split("(")[0]
'this is so cool '
>>> s="this is so cool (234) test (123)"
>>> for i in s.split(")"):
...  if "(" in i:
...     print i.split("(")[-1]
...
234
123
3

听起来你可以这样做:

re.findall('[^()]+', mystring)

分割也可以这样实现:

re.split('[()]', mystring)

无论哪种方式,括号前的文字都会成为结果数组中的第一个项目,而第一个括号内的文字则会成为第二个项目。

8

直到这个括号为止: regex = re.compile("(.*?)\s*\(")

在第一个括号里面: regex = re.compile(".*?\((.*?)\)")

补充: 单个正则表达式版本: regex = re.compile("(.*?)\s*\((.*?)\)")

示例输出:

>>> import re
>>> r1 = re.compile("(.*?)\s*\(")
>>> r2 = re.compile(".*?\((.*?)\)")
>>> text = "this is so cool (234)"
>>> m1 = r1.match(text)
>>> m1.group(1)
'this is so cool'
>>> m2 = r2.match(text)
>>> m2.group(1)
'234'
>>> r3 = re.compile("(.*?)\s*\((.*?)\)")
>>> m3 = r3.match(text)
>>> m3.group(1)
'this is so cool'
>>> m3.group(2)
'234'
>>> 

当然要注意,这个方法在有多个括号的情况下不会正常工作,因为它只期待一个被括起来的文本块(就像你的例子那样)。匹配任意数量的开括号和闭括号的语言并不是常规的。

撰写回答