首页 > 解决方案 > Python如何从字符串中提取用括号括起来的数据

问题描述

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

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

例子:

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('(') 然后开始获取项目,但试图为这种情况找到更好的解决方案,因为我会解析大量的字符串。

标签: python

解决方案


您可以使用正则表达式

这是我的写法:

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)

推荐阅读