【问题标题】:Python how to extract data surrounded by parenthesis from a string [duplicate]Python如何从字符串中提取用括号括起来的数据[重复]
【发布时间】:2026-01-13 11:15:01
【问题描述】:

我正在尝试找到一种智能且快速的解决方案来从字符串中提取一些数据。

基本上我想获取'(...)'中的所有文本

例子:

ex_string= "My Cell Phone number is (21) 99715-5555"
return = 21

ex_string2 = "Apple (AAPL) have a great quarterly, but Microsoft (MSFT) have a better one"
return = ['AAPL', 'MSFT'] 

ex_string3 = "Hello World"
return = None

诀窍是一些字符串只有一个项目,另一个会有更多,而另一个没有。

我知道我可以 .split('(') 然后开始获取项目,但试图为这种情况找到更好的解决方案,因为我会解析大量的字符串。

【问题讨论】:

  • re.findall(r"\((\w+)\)", ex_string2 )?
  • 刚刚意识到这是一个骗局

标签: python


【解决方案1】:

您可以使用regular expressions

我会这样写:

import re

def find_enclosed(s): 
    # find all matches
    matches = re.findall(r"\((.*?)\)", s) 
    # if there are no matches return None
    if len(matches) == 0:
        return None
    # if it is a valid number change its type to a number
    for i in range(len(matches)):
        try:
            matches[i] = int(matches[i])
        except:
            pass
    # if there is only one match return it without a list
    if len(matches) ==  1:
        return matches[0]
    
    return matches

这就是你将如何使用它:

ex_string= "My Cell Phone number is (21) 99715-5555"
ex_string2 = "Apple (AAPL) have a great quarterly, but Microsoft (MSFT) have a better one"

matches1 = find_enclosed(ex_string1)
matches2 = find_enclosed(ex_string2)

print(matches1)
print(matches2)

【讨论】:

  • 谢谢!非常适合...
  • @FelipeCid 不要忘记将问题标记为已回答 :)
【解决方案2】:

您应该使用 RegExp 来获取括号内的数据。可以使用名为 re 的内置 Python 模块。 regex101.com 站点是一个非常有用的正则表达式测试器,您可以在其中为自己创建正确的正则表达式。

代码:

import re

# It founds everything inside parenthesis (numbers, strings, special characters etc...).
my_regexp = r"\((.*?)\)"

test_string_1 = "My Cell Phone number is (21) 99715-5555"
test_string_2 = "Apple (AAPL) have a great quarterly, but Microsoft (MSFT) have a better one"
test_string_3 = "Not parenthesis"

print(re.findall(my_regexp, test_string_1))
print(re.findall(my_regexp, test_string_2))
print(re.findall(my_regexp, test_string_3))

输出:

>>> python3 test.py 
['21']
['AAPL', 'MSFT']
[]

【讨论】: