Skip to main content
 首页 » 编程设计

python之在python中使用正则表达式提取多个特定单词之间的子字符串

2025年05月04日38kerrycode

正则子串

我想提取Phone, Fax, Mobile 我从字符串中获取如果不是它可以返回空字符串。我想要 3 个来自任何给定文本字符串示例的电话、传真、手机列表,如下所示。

ex1 = "miramar road margie shoop san diego ca 12793 manager  phone 6035550160 fax 6035550161 mobile 6035550178  marsgies travel  wwwmarpiestravelcom" 
ex2 = "david packard electrical engineering  350 serra mall room 170 phone 650 7259327  stanford university fax 650 723 1882 stanford california 943059505 ulateecestanfordedu" 
ex3 = "stanford  electrical  engineering  vijay chandrasekhar  electrical engineering 17 comstock circle apt 101  stanford ca 94305  phone 9162210411" 

像这样使用正则表达式是可能的:

phone_regex  = re.match(".*phone(.*)fax(.*)mobile(.*)",ex1) 
phone = [re.sub("[^0-9]","",x) for x in phone_regex.groups()][0] 
mobile = [re.sub("[^0-9]","",x) for x in phone_regex.groups()][2] 
fax = [re.sub("[^0-9]","",x) for x in phone_regex.groups()][1] 

Result from ex1:
phone = 6035550160
fax = 6035550161
mobile = 6035550178

ex2 没有mobile 条目,所以我得到:

Traceback (most recent call last):
phone = [re.sub("[^0-9]", "", x) for x in phone_regex.groups()][0]
AttributeError: 'NoneType' object has no attribute 'groups'

问题
我需要一个更好的正则表达式解决方案,因为我是正则表达式的新手, 或者,一个解决方案,捕获 AttributeError 并分配 null string。

请您参考如下方法:

你可以像这样使用一个简单的re.findall:

dict(re.findall(r'\b({})\s*(\d+)'.format("|".join(keys)), ex)) 

正则表达式看起来像

\b(phone|fax|mobile)\s*(\d+) 

参见 regex demo online .

图案细节

  • \b - 单词边界
  • (phone|fax|mobile) - 第 1 组:列出的单词之一
  • \s* - 0+ 个空格
  • (\d+) - 第 2 组:一个或多个数字

参见 Python demo :

import re 
exs = ["miramar road margie shoop san diego ca 12793 manager  phone 6035550160 fax 6035550161 mobile 6035550178  marsgies travel  wwwmarpiestravelcom", 
   "david packard electrical engineering  350 serra mall room 170 phone 650 7259327  stanford university fax 650 723 1882 stanford california 943059505 ulateecestanfordedu",  
   "stanford  electrical  engineering  vijay chandrasekhar  electrical engineering 17 comstock circle apt 101  stanford ca 94305  phone 9162210411"] 
keys = ['phone', 'fax', 'mobile'] 
for ex in exs: 
    res = dict(re.findall(r'\b({})\s*(\d+)'.format("|".join(keys)), ex)) 
    print(res) 

输出:

{'fax': '6035550161', 'phone': '6035550160', 'mobile': '6035550178'} 
{'fax': '650', 'phone': '650'} 
{'phone': '9162210411'}