Python:定义正则表达式的并集

day*_*mer 5 python regex

我有一个类似的模式列表

list_patterns = [': error:', ': warning:', 'cc1plus:', 'undefine reference to']
Run Code Online (Sandbox Code Playgroud)

我想要做的是生成一个所有这些联合的联合,产生一个匹配list_patterns[ 中的每个元素的正则表达式[但可能不匹配任何不在list_patterns中 - msw]

re.compile(list_patterns)
Run Code Online (Sandbox Code Playgroud)

这可能吗?

cle*_*tus 10

有几种方法可以做到这一点.最简单的是:

list_patterns = [': error:', ': warning:', 'cc1plus:', 'undefine reference to']
string = 'there is an : error: and a cc1plus: in this string'
print re.findall('|'.join(list_patterns), string)
Run Code Online (Sandbox Code Playgroud)

输出:

[': error:', 'cc1plus:']
Run Code Online (Sandbox Code Playgroud)

只要连接你的搜索模式不会打破正则表达式(例如,如果其中一个包含正则表达式特殊字符,如左括号),这是很好的.你可以这样处理:

list_patterns = [': error:', ': warning:', 'cc1plus:', 'undefine reference to']
string = 'there is an : error: and a cc1plus: in this string'
pattern = "|".join(re.escape(p) for p in list_patterns)
print re.findall(pattern, string)
Run Code Online (Sandbox Code Playgroud)

输出是一样的.但这样做是通过每个模式re.escape()来逃避任何正则表达式的特殊字符.

现在使用哪一个取决于您的模式列表.它们是正则表达式,因此可以假设有效吗?如果是这样,第一个可能是合适的.如果它们是字符串,请使用第二种方法.

对于第一个,它变得更复杂,但是因为通过连接几个正则表达式,您可能会更改分组并具有其他意外的副作用.

  • 这假设list_patterns具有要匹配的文字字符串,而不是正则表达式.(这可能是也可能不是OP想要的......这个问题有点不清楚.) (2认同)