以有效的方式组合正则表达式 python

Combine in an efficient way regex python

设置

我动态创建了一个正则表达式列表,即regex_list。 列表中的每个正则表达式肯定会与应用的文本进行至少一次匹配。 可能会发生列表中的某些正则表达式等于。

regex_list = []
for f in foo: # foo is a list of strings e.g. foo = ['foo1', 'foo2', 'foo1', ...]
    # f is a valid expression to be used inside the regex
    regex_list.append(f'[^.]*?{f}[^.]*\.')

regex = re.compile('|'.join(regex_list), flags=re.DOTALL)
result = re.findall(regex, text)

问题

  1. regex_list 中的某些正则表达式可能等于
  2. regex_list 中的正则表达式与 OR 运算符组合在一起

对于列表中存在另一个副本的正则表达式,仅捕获文本中的第一个匹配项。

问题

一种解决方法是使用 for 循环单独应用每个正则表达式,但速度非常慢。

有什么好的方法可以结合正则表达式并使它们匹配所有可能的内容吗?

偶然发现使用 re module, while it's surprisingly faster using the regex module.

在 for 循环中单独应用每个正则表达式非常慢