简体   繁体   English

查找两个字符串之间的最短匹配

[英]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 .我有一个很大的日志文件,我想提取两个字符串之间的多行字符串: startend

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 :编辑:关于现实生活计算复杂性的附加信息

  • actual file size: 2GB实际文件大小:2GB
  • occurrences of 'start': ~ 12 M, evenly distributed “开始”的出现次数:~ 12 M,均匀分布
  • occurences of 'end': ~800, near the end of the file. 'end' 的出现次数:~800,接近文件末尾。

This regex should match what you want:这个正则表达式应该符合你想要的:

(start((?!start).)*?end)

Use re.findall method and single-line modifier re.S to get all the occurences in a multi-line string:使用re.findall方法和单行修饰符re.S获取多行字符串中的所有出现:

re.findall('(start((?!start).)*?end)', text, re.S)

See a test here .在这里查看测试。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM