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

时间:2019-01-14 20:11:37

标签: python regex python-3.x

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

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

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

1 个答案:

答案 0 :(得分:2)

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

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

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

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

(嗯,无论如何,这里使用字典并不是真正有用。将来如何使用正则表达式作为键?)

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

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

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

或使用pattern regex属性重建模式:

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