Pythonic连接正则表达式对象的方法

时间:2014-02-28 18:16:00

标签: python regex

我有python正则表达式对象 - 比如,re_first和re_second - 我想连接。

import re
FLAGS_TO_USE = re.VERBOSE | re.IGNORECASE
re_first = re.compile( r"""abc #Some comments here """, FLAGS_TO_USE )
re_second = re.compile( r"""def #More comments here """, FLAGS_TO_USE )

我想要一个与上述正则表达式中的任何一个匹配的正则表达式。到目前为止,我有

pattern_combined = re_first.pattern + '|' + re_second.pattern
re_combined = re.compile( pattern_combined, FLAGS_TO_USE ) 

对于更多的python对象,这不能很好地扩展。我最终看起来像是:

pattern_combined = '|'.join( [ first.pattern, second.pattern, third.pattern, etc ] )

关键是要连接的列表可能很长。任何想法如何避免这种混乱? 提前谢谢。

3 个答案:

答案 0 :(得分:10)

我认为您不会找到一个不涉及首先使用正则表达式对象创建列表的解决方案。我会这样做:

# create patterns here...
re_first = re.compile(...)
re_second = re.compile(...)
re_third = re.compile(...)

# create a list with them
regexes = [re_first, re_second, re_third]

# create the combined one
pattern_combined = '|'.join(x.pattern for x in regexes)

当然,您也可以这样做:组合模式然后编译,如下所示:

pattern1 = r'pattern-1'
pattern2 = r'pattern-2'
pattern3 = r'pattern-3'

patterns = [pattern1, pattern2, pattern3]

compiled_combined = re.compile('|'.join(x for x in patterns), FLAGS_TO_USE)

答案 1 :(得分:2)

将它们放在列表中,然后

'|'.join(your_list)

答案 2 :(得分:0)

一个人也可以直接串联r字符串,例如:

prep_re = r"\b" + r"\b|\b".join(prepositions) + r"\b"
re.findall(prep_re, paragraph, re.IGNORECASE)