我有一个预定义的字符串列表,我想在一个大文本文件中匹配它。问题是其中许多字符串确实存在于文本中,但被我想保留的虚假字符/html-xml标签打断。
例如,我想匹配"联合国总部"它可以以以下形式存在于文本中:
United Nations & Headquarters
United <br> Nations Headquarters
United Natio<b>ns Hea</b>dquarters
我基本上需要知道这些字符串的位置,稍后我会处理虚假字符。对于不间断的字符串,我要做的是:
sting_locations=[v.span() for v in re.finditer(our_string,text)]
是否可以为正则表达式设置一些设置来以某种方式忽略这些中断,或者解决方案是什么?
import re
text = """United Nations & Headquarters
United <br> Nations Headquarters
United Natio<b>ns Hea</b>dquarters"""
s = "United Nations Headquarters"
r = re.compile(".*?".join(s))
print([v.span() for v in r.finditer(text)])
关键是 ".*?".join(s)
,它在每对连续的s
字符之间插入.*?
,以将其转换为正则表达式。
如果要限制允许的中断,您可能更愿意稍微收紧.*?
。
有几个解决方案可以避免灾难性的回溯并允许任意数量的中断!
解决方案 A
这是最干净的解决方案,但需要正则表达式模块(在此处赢得二进制文件)。它使用原子分组,(?>...)
,以避免回溯:
import regex
strExampleFile = '''United Nations & Headquarters
United <br> Nations Headquarters
United Natio<b>ns Hea</b>dquarters'''
strSearch = 'United Nations Headquarters'
strRegex = regex.sub(r'((?<!^).)',r'(?>[sS]*?(?=1))1',strSearch)
rexRegex = regex.compile(strRegex)
print([objMatch.span() for objMatch in rexRegex.finditer(strExampleFile)])
解决方案 B
如果您既没有安装也不想安装正则表达式模块,则 re 可用于模拟原子分组。但是,搜索字符串现在限制为最多 100 个字符:
import re
strExampleFile = '''United Nations & Headquarters
United <br> Nations Headquarters
United Natio<b>ns Hea</b>dquarters'''
strSearch = 'United Nations Headquarters'
strRegex = re.sub(r'((?<!^).)',r'(?=([sS]*?(?=1)))\##1',strSearch)
for numBackReference in range(1,len(strSearch)) :
strRegex = strRegex.replace("##", str(numBackReference),1)
rexRegex = re.compile(strRegex)
print([objMatch.span() for objMatch in rexRegex.finditer(strExampleFile)])
注意:正如 femtoRgon所指出的,这两种方法都可能返回误报。