首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >python regex在第一项和最后一项之间保持一行。

python regex在第一项和最后一项之间保持一行。
EN

Stack Overflow用户
提问于 2016-03-18 03:02:37
回答 4查看 72关注 0票数 0

所以我有一个文本文件,有几个字符串显示为“继续阅读主要故事”。假设文本如下所示:

第1部分 继续读主要故事 第2部分 继续读主要故事 第3部分 继续读主要故事 继续读主要故事 第4部分

我想要的是part2和part3,如下所示:

第2部分 继续读主要故事 第3部分

因为它是在“继续阅读故事”的第一次出现和最后一次出现之间。现在,我已经考虑使用以下代码:

代码语言:javascript
复制
my_regex = re.compile("(Continue reading the main story)"+
                   ".*"+ # match as many chars as possible
                   "(Continue reading the main story)",
                   re.DOTALL)
new_str = my_regex.sub("\1\2", text)

但是它不起作用。怎么改正呢?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2016-03-18 03:25:04

如果你知道你的短信不是以“继续.”开头的不以“继续.”结尾,你可以用“继续.”分开字符串,移除第一项、最后一项和空项,您将得到所需的东西。

代码语言:javascript
复制
import re
text = """\
part 1

Continue reading the main story

part 2

Continue reading the main story

part 3

Continue reading the main story

Continue reading the main story

part 4
"""

parts = re.split('Continue reading the main story', text)
print(parts)
# Ignore first and last part, test for and ignore
# empty (all whitespace) strings
innerparts = [part for part in parts[1:-1] if part.strip()]
print("".join(innerparts))

结果:

代码语言:javascript
复制
part 2



part 3

(有相当多的新行,因为输入就是这样的。如果您想摆脱这种情况,可以使用part.strip() )。)

票数 0
EN

Stack Overflow用户

发布于 2016-03-18 03:21:33

试着跟着雷杰斯。我使用的是后视功能和前瞻性功能:

代码语言:javascript
复制
rx = "(?<=part 1\n{2}Continue reading the main story).*(?=Continue reading the main story[\r\n]+part 4)"

for match in re.finditer(rx, text, re.IGNORECASE | re.DOTALL | re.MULTILINE):
    print(match.group().strip())

根据您给定的文本,它将打印

代码语言:javascript
复制
part 2

Continue reading the main story

part 3

Continue reading the main story
票数 0
EN

Stack Overflow用户

发布于 2016-03-18 03:46:56

一个简单的re.findall()就可以做到这一点。

代码语言:javascript
复制
rgx = r'Continue reading the main story(.*)Continue reading the main story'
match = re.findall(rgx, text, re.DOTALL)
if match:
    result = match[0].strip()
    print(result)

根据您给定的文本,这将打印

代码语言:javascript
复制
part 2

Continue reading the main story

part 3

Continue reading the main story
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36075384

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档