所以我有一个文本文件,有几个字符串显示为“继续阅读主要故事”。假设文本如下所示:
第1部分 继续读主要故事 第2部分 继续读主要故事 第3部分 继续读主要故事 继续读主要故事 第4部分
我想要的是part2和part3,如下所示:
第2部分 继续读主要故事 第3部分
因为它是在“继续阅读故事”的第一次出现和最后一次出现之间。现在,我已经考虑使用以下代码:
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)但是它不起作用。怎么改正呢?
发布于 2016-03-18 03:25:04
如果你知道你的短信不是以“继续.”开头的不以“继续.”结尾,你可以用“继续.”分开字符串,移除第一项、最后一项和空项,您将得到所需的东西。
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))结果:
part 2
part 3(有相当多的新行,因为输入就是这样的。如果您想摆脱这种情况,可以使用part.strip() )。)
发布于 2016-03-18 03:21:33
试着跟着雷杰斯。我使用的是后视功能和前瞻性功能:
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())根据您给定的文本,它将打印
part 2
Continue reading the main story
part 3
Continue reading the main story发布于 2016-03-18 03:46:56
一个简单的re.findall()就可以做到这一点。
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)根据您给定的文本,这将打印
part 2
Continue reading the main story
part 3
Continue reading the main storyhttps://stackoverflow.com/questions/36075384
复制相似问题