Skip to main content
 首页 » 编程设计

python之如何使用 findall 打印正则表达式的结果

2025年02月15日45shihaiming

对于使用 Python 的正则表达式有点陌生,我正在尝试解析下面的数据。

代码

thing = soup.find_all('div', {'class' : 'matchheader'}) 
thing1 = str(thing) 
print(thing1) 

给我

  1. GSL - <b>Global Ship Lease Inc</b> [N/A] - Matched DCIX from 07/27/16 to 12/01/16 
  </div>, <div class="matchheader"> 
  2. SBGI - <b>Sinclair Broadcast Group, Inc.</b> [Media] - Matched DCIX from 07/27/16 to 12/01/16 
  </div>, <div class="matchheader"> 
  3. WSTC - <b>West Corporation</b> [+2] - Matched DCIX from 07/27/16 to 12/01/16 
  </div>, <div class="matchheader"> 
  4. TGNA - <b>TEGNA Inc.</b> [N/A] - Matched DCIX from 07/27/16 to 12/01/16 
  </div>, <div class="matchheader"> 
  5. MLI - <b>MUELLER INDUSTRIES INC</b> [Manufacturing] - Matched DCIX from 07/27/16 to 12/01/16 

现在是正则表达式

pattern = "([A-Z])[A-Z]{2,5}(?![A-Z])" 
match = re.findall(pattern,thing1) 
print(match) 

我期待的结果是

['GSL', 'SBGI', 'WSTC', 'TGNA', 'MLI'] 

但是我得到的结果是

['G', 'D', 'S', 'D', 'W', 'D', 'T', 'T', 'D', 'M', 'U', 'S', 'I', 'D'] 

我很确定第二个 D 来自第一行的 DCIX。

问题是我使用的正则表达式模式,使用re.findall,还是print(match)?

如有任何帮助,我们将不胜感激。

请您参考如下方法:

您的正则表达式将匹配每组连续的大写字母,然后仅返回每组的第一个字母。相反,您可能打算每行只返回这些组中的第一个。

您可以改为使用前缀 ^.*?([A-Z]{2,5}) 在 ^ 行的开头找到最短序列。 *?(使用 re.M 用于多行模式)后跟一组大写字母 ([A-Z]{2,5}) ,如果有的话,然后返回那个组。

>>> re.findall("^.*?([A-Z]{2,5})", thing1, re.M) 
['GSL', 'SBGI', 'WSTC', 'TGNA', 'MLI']