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

编程入门 行业动态 更新时间:2024-10-07 16:20:09
本文介绍了查找两个字符串之间的最短匹配项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

在此处查看测试.

更多推荐

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

本文发布于:2023-11-30 13:34:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1650170.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:最短   字符串   两个

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!