首页 > 解决方案 > 使用 re.compile 编译列表中的多个字符串

问题描述

我想编制这份清单

list_serv = ["no","none","nothing","never"]

但我无法做到这一点,所以我必须单独键入该列表的每个元素,如下所示

compiled_list_serv = re.compile(r'no\b|not\b|none\b|nothing\b')

有人可以建议我使用 Python 编写一个高效的代码,以便我可以一次性编译列表“list_serv”中的所有元素吗?

生成的编译应如下所示:

re.compile(r'no\b|not\b|none\b|nothing\b', re.UNICODE)

标签: regexpython-3.x

解决方案


你想达到什么目的?

从给定的代码中,您可以这样做:

re.compile("|".join(list_serv), re.UNICODE)

推荐阅读