无奈re.search()只匹配首次;re.findall()返回结果为搜索关键字,虽然可以用.{n}key_word.{n}去匹配但是灵活性很差,所以。。。
用python写了一个粗略的,实际应用要做出相应修改的,不然会有很多bug跑出来,例如溢出、死循环~~
import os
import traceback
def find_cut(str1,str2):
count=5#定义同段文本的重复匹配次数
s=""
while count:
try:
temp=str2.find(str1)
if (temp+1):
s=s+str2[temp-5:temp+len(str1)+5]+'\n'#把搜索关键字的左右5个距离的文本cut下来,并转行
str2=str2[temp+5:]
except:
continue
s=s+'None'
count=count-1
return s
def main():
patten='python'#搜索关键字
search_string='00000python00000-11111python11111-22222python22222'#要搜索文本
print(find_cut(patten,search_string))
main()
输出结果: