本文介绍了查找两个字符串之间的最短匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个很大的日志文件,我想在两个字符串之间提取一个多行字符串:start 和 end.
I have a large log file, and I want to extract a multi-line string between two strings: start and end.
以下是来自 inputfile 的示例:
The following is sample from the inputfile:
start spam start rubbish start wait for it... profit! here end start garbage start second match win. end所需的解决方案应该打印:
The desired solution should print:
start wait for it... profit! here end start second match win. end我尝试了一个简单的正则表达式,但它从start spam 返回了所有内容.这应该怎么做?
I tried a simple regex but it returned everything from start spam. How should this be done?
关于现实生活中计算复杂性的其他信息:
- 实际文件大小:2GB
- 开始"的出现次数:~ 12 M,均匀分布
- 'end' 的出现次数:~800,接近文件末尾.
这个正则表达式应该符合你的要求:
This regex should match what you want:
(start((?!start).)*?end)使用 re.findall 方法和单行修饰符 re.S 获取多行字符串中的所有出现:
Use re.findall method and single-line modifier re.S to get all the occurences in a multi-line string:
re.findall('(start((?!start).)*?end)', text, re.S)在此处查看测试.
更多推荐
查找两个字符串之间的最短匹配
发布评论