gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 05:19:05 25 4
gpt4 key购买 nike

对于使用 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']

关于python - 如何使用 findall 打印正则表达式的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40941903/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com