[英]Find shortest matches between two strings
I have a large log file, and I want to extract a multi-line string between two strings: start
and end
.我有一个很大的日志文件,我想提取两个字符串之间的多行字符串:
start
和end
。
The following is sample from the inputfile
:以下是输入文件中的
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
I tried a simple regex but it returned everything from start spam
.我尝试了一个简单的正则表达式,但它返回了从
start spam
的所有内容。 How should this be done?这应该怎么做?
Edit: Additional info on real-life computational complexity :编辑:关于现实生活计算复杂性的附加信息:
Do it with code - basic state machine:用代码来做 - 基本状态机:
open = False
tmp = []
for ln in fi:
if 'start' in ln:
if open:
tmp = []
else:
open = True
if open:
tmp.append(ln)
if 'end' in ln:
open = False
for x in tmp:
print x
tmp = []
This is tricky to do because by default, the re
module does not look at overlapping matches.这很棘手,因为默认情况下,
re
模块不查看重叠匹配。 Newer versions of Python have a new regex
module that allows for overlapping matches.较新版本的 Python 有一个新的
regex
模块,允许重叠匹配。
https://pypi.python.org/pypi/regex https://pypi.python.org/pypi/regex
You'd want to use something like你想使用类似的东西
regex.findall(pattern, string, overlapped=True)
If you're stuck with Python 2.x or something else that doesn't have regex
, it's still possible with some trickery.如果您坚持使用 Python 2.x 或其他没有
regex
东西,仍然可以使用一些技巧。 One brilliant person solved it here:一位聪明的人在这里解决了这个问题:
Python regex find all overlapping matches? Python正则表达式找到所有重叠的匹配项?
Once you have all possible overlapping (non-greedy, I imagine) matches, just determine which one is shortest, which should be easy.一旦你有所有可能的重叠(非贪婪,我想)匹配,只需确定哪个最短,哪个应该很容易。
You could do (?s)start.*?(?=end|start)(?:end)?
你可以做
(?s)start.*?(?=end|start)(?:end)?
, then filter out everything not ending in "end". ,然后过滤掉所有不以“end”结尾的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.