regex - 当模式具有相似文本时,如何使用 RegEx 在 Python 中获取所有匹配项?

标签 regex python-2.7

我有以下示例字符串:

this is a test of the loss of offsite power

我有以下标签:

offsite power, loss of offsite power

我正在尝试从字符串中获取所有匹配项。但是当我有这段代码时:

import re

description = 'this is a test of the loss of offsite power'
all_tags = ['offsite power', 'loss of offsite power']
reg_ex = '|'.join(['\\b%s\\b' % t for t in all_tags])

expression = re.compile(reg_ex, re.IGNORECASE)

matches = re.findall(expression, description)

results = [m for m in matches]

print results

我的结果如下:

['loss of offsite power']

我需要获取标签的两个实例。我知道我可以通过遍历每个标签然后搜索每个标签的描述来做到这一点,但是有没有办法在一次搜索中做到这一点?

我的代码适用于 Python 2.7,但我也接受 Python 3 的答案。

注意:我的最终关键词列表大约有 2000 个与上述类似的词组。

最佳答案

非常简单:使用较新的 regex Matthew Barnett 的模块允许重叠匹配。在 Python 中:

import regex as re
string = 'this is a test of the loss of offsite power'

all_tags = ['offsite power', 'loss of offsite power']
reg_ex = '|'.join(['\\b%s\\b' % t for t in all_tags])

expression = re.compile(reg_ex, re.IGNORECASE)

# mind overlapped=True !
matches = re.findall(expression, string, overlapped=True)
print matches
# ['loss of offsite power', 'offsite power']

要获取模块,只需在命令行上执行 pip install regex。它也适用于 re.finditer()

关于regex - 当模式具有相似文本时,如何使用 RegEx 在 Python 中获取所有匹配项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36748572/

相关文章:

python - 从字符串python正则表达式中提取匹配组

java - 使用正则表达式删除 MS Word 链接

javascript - 满足条件时正则表达式匹配逗号

python - 如何在 Python 脚本中获得导入类的相同作用域?

python - 对象类型和访问嵌套值

python-2.7 - Pandas - 使用自定义日历获取日期之间的工作日?

regex - PostgreSQL UPDATE 子字符串替换

javascript - 用谷歌脚本中的条件替换字符串

python - Python中两组元组的区别

python-2.7 - 带有 flask 身份验证 :multiple HTTP method with different authentication 的 flask Restful