是否可以对多个re.compile()输出进行或运算?

问题描述 投票:0回答:1

假设我已经有一些由re.compile()创建的对象。

x = re.compile('abc')
y = re.compile('abd')

是否可以将x和y或为新对象?

z = re.compile('abc|abd')

请注意,我使用的是原始正则表达式“ abc”和“ abd”。但是在实际情况下,我可能不认识它们,只知道xy

我想将原始正则表达式合并为一个新的正则表达式对象。我不想使用any()之类的东西来检查每个正则表达式,因为组合的正则表达式应该能更快地工作。

python regex boolean-logic
1个回答
-1
投票

最简单的方法是将它们与适当的正则表达式语法进行字符串组合:

x = re.compile('abc')
y = re.compile('abd')
z = re.compile('(?:%s)|(?:%s)' % (x.pattern, y.pattern))

您也可以在列表上执行相同的操作:

regexes = [
    re.compile('abc'),
    re.compile('abd')
]
z = re.compile('|'.join('(?:%s)' % i.pattern for i in regexes))

注意:这将不是考虑re.compilere.I之类的re.M选项。您可能还希望包括这些内容,如果选项不匹配,则会抛出错误。

def join_regexes(regexes):
    patterns = []
    for i, regex in enumerate(regexes):
        if not i:
            flags = regex.flags
        elif flags != regex.flags:
            raise Exception('regex flags need to match')
        patterns.append(regex.pattern)
    pattern = '|'.join('(?:%s)' % p for p in patterns)
    return re.compile(pattern, flags)
© www.soinside.com 2019 - 2024. All rights reserved.