python regex获取所有文本直到a(,并获取括号内的文本

2024-04-26 21:16:16 发布

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

我需要两个regex操作的帮助。

  1. 获取所有文本,直到出现一个左括号。

例如,“太酷了(234)”=>;“太酷了”

  1. 把文本放在括号里,所以数字'234'

Tags: 文本gt数字regex括号
1条回答
网友
1楼 · 发布于 2024-04-26 21:16:16

直到帕伦:regex = re.compile("(.*?)\s*\(")

在第一组parens中:regex = re.compile(".*?\((.*?)\)")

编辑:单个regex版本: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'
>>> 

当然要注意,这对于多组paren是行不通的,因为它只需要一个带括号的文本块(根据您的示例)。任意递归的开闭parens匹配语言是不规则的。

网友
2楼 · 发布于 2024-04-26 21:16:16

不需要正则表达式。

>>> 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楼 · 发布于 2024-04-26 21:16:16

听起来你可以这么做:

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

拆分也可以:

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

无论哪种方式,第一个括号前的文本都将是结果数组中的第一项,第一组parens中的文本将是第二项。

相关问题 更多 >