Skip to main content
 首页 » 编程设计

python之使用 join 匹配多个正则表达式

2024年09月03日38kevingrace

我有一本字典,它的键都是预编译的正则表达式。我想将字符串与这些正则表达式中的任何一个相匹配。

在研究时,我发现您可以通过使用 join 方法连接多个正则表达式来匹配它们。但是当我这样做时,我得到一个类型错误:

import re 
 
regex1 = re.compile("regex1.*") 
regex2 = re.compile("regex2\d") 
re_dict = {regex1 : "stuff", regex2 : "otherstuff"} 
match_multiple = "|".join(list(re_dict.keys())) 
string = 'regex25' 
if re.match(match_multiple, string): 
    print("matched") 

这给出:

Traceback (most recent call last): 
   File "./a.py", line 7, in <module> 
    match_multiple = "|".join(list(re_dict.keys())) 
TypeError: sequence item 0: expected str instance, re.Pattern found 

请您参考如下方法:

str.join 适用于 strings,不适用于 re 对象。加入然后编译。

regex1 = "regex1.*" 
regex2 = "regex2\d" 
re_dict = {regex1 : "stuff", regex2 : "otherstuff"} 
match_multiple = re.compile("|".join(re_dict)) 

请注意,dict 没有排序(除非您运行的是 python 3.6),因此如果表达式的顺序很重要,您的代码可能不正确

还要注意从 list(re_dict.keys()) 到 re_dict 的简化,因为迭代字典会产生它的键。无需显式调用 keys 或转换为 list。

(好吧,反正这里用字典也没什么用,以后怎么用regex做key?)

如果您只能访问预编译表达式,则使用any

“模拟”正则表达式 或
if any(r.match(string) for r in re_dict): 

any 短路,因此只要一个正则表达式匹配,它就会以 True 退出。

或者使用 pattern 正则表达式属性重建模式:

match_multiple = re.compile("|".join([r.pattern for r in re_dict]))