Python多行正则表达式

13

我该如何提取出给定词序列第一次出现之前的所有字符(包括换行符)?例如,对于以下输入:

输入文本:

"shantaram is an amazing novel.
It is one of the best novels i have read.
the novel is written by gregory david roberts.
He is an australian"

我想从shantaram中提取文本到第一次出现在第二行的the

输出必须为-

shantaram is an amazing novel.
It is one of the

我已经尝试了一整个上午。我可以编写提取到特定字符之前所有字符的表达式,但是在这里,如果我使用类似于下面的表达式:

re.search("shantaram[\s\S]*the", string)

它不能跨越换行符匹配。


你尝试过什么吗? - Rohit Jain
1
要求提供代码的问题必须展示对问题的基本理解。请包括尝试过的解决方案,为什么它们不起作用以及期望的结果。 - zero323
我从早上开始一直在尝试。我可以编写表达式以提取所有字符,直到遇到特定字符为止。但是如果我使用像以下这样的表达式- re.search("shantaram [\ s \ S] * the", string) 它不起作用,因为“the”是[\ s \ S]的一部分,而提取没有发生。 - AKASH
3个回答

27
你想使用DOTALL选项来跨越换行匹配。从doc.python.org

re.DOTALL

使点号(.)特殊字符匹配任何字符,包括换行符;如果没有此标志,则点号(.)将匹配除换行符以外的任何字符。

演示:
In [1]: import re

In [2]: s="""shantaram is an amazing novel.
It is one of the best novels i have read.
the novel is written by gregory david roberts.
He is an australian"""

In [3]: print re.findall('^.*?the',s,re.DOTALL)[0]
shantaram is an amazing novel.
It is one of the

6

请使用以下正则表达式:

re.search("shantaram[\s\S]*?the", string)

替代

re.search("shantaram[\s\S]*the", string)
唯一的区别在于'?'符号。通过使用'?'(例如*?,+?),您可以防止最长匹配。

1
一种不使用正则表达式的解决方案:
from itertools import takewhile
def upto(a_string, stop):
    return " ".join(takewhile(lambda x: x != stop and x != "\n".format(stop), a_string))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,