首页 > 解决方案 > python 正则表达式使用 findall 查找多个匹配项

问题描述

我需要找到 2 个正则表达式模式,但我没有找到让它工作的方法

我有一个变量可能是其中之一(例如更多)

repository = "Red Hat Enterprise Linux Extended Update Support 7.2"

repository = "Red Hat Enterprise Linux 7"

我需要找到具有该模式的两个存储库:

regex_rhel = 'Red Hat Enterprise Linux' + " " + str(major_version)

regex_eus = 'Red Hat Enterprise Linux Extended Update Support' + " " + str(rhel_ver)

我试过 findall ,但得到:

eus_latest_repos = re.findall(r'"Red Hat Enterprise Linux' + " " + str(major_version)|('Red Hat Enterprise Linux Extended Update Support' + " " + str(rhel_ver),repository))
                    print(eus_latest_repos)


TypeError: unsupported operand type(s) for |: 'str' and 'tuple'

标签: python

解决方案


如果我理解你需要一个正则表达式来从字符串中提取 repo。

演示:

import re
repository = "Red Hat Enterprise Linux Extended Update Support 7.2"
repository = "Red Hat Enterprise Linux 7"


s = "sadasdjkasdflsdfsdf;ljk lsjdlsdfj Red Hat Enterprise Linux Extended Update Support 7.2 kjshdklsdhksdjf sdfdfdfgdfg Red Hat Enterprise Linux 7 sdfsdfkl;dfjsgsdfg adfadsfladjksfds"


print(re.findall("Red Hat Enterprise Linux Extended Update Support\s+\d*\.?\d+|Red Hat Enterprise Linux\s+\d+", s))

输出:

['Red Hat Enterprise Linux Extended Update Support 7.2', 'Red Hat Enterprise Linux 7']

推荐阅读