首页 > 解决方案 > re.findall 多行python

问题描述

re.findall 和 re.M 没有找到我要搜索的多行

我正在尝试从文件中提取与模式匹配的所有多行字符串

文件中的示例book.txt

Title: Le Morte D'Arthur, Volume I (of II)
       King Arthur and of his Noble Knights of the Round Table

Author: Thomas Malory

Editor: William Caxton

Release Date: March, 1998  [Etext #1251]
Posting Date: November 6, 2009

Language: English

Title: Pride and Prejudice

Author: Jane Austen

Posting Date: August 26, 2008 [EBook #1342]
Release Date: June, 1998
Last Updated: October 17, 2016

Language: English

下面的代码只返回第一行Le Morte D'Arthur, Volume I (of II)

re.findall('^Title:\s(.+)$', book, re.M)

我期望输出是

[' Le Morte D'Arthur, Volume I (of II)\n King Arthur and of his Noble Knights of the Round Table', ' Pride and Prejudice']

澄清一下,
- 第二行是可选的,它存在于某些文件中,而不存在于其他文件中。在第二行之后还有更多我不想阅读的文本。
-re.findall(r'Title: (.+\n.+)$', text, flags=re.MULTILINE)如果第二行只是空白,则使用有效但失败。
- 我正在运行 python3.7。
- 我正在将 txt 文件转换为字符串,然后re在 str 上运行。
- 以下也不起作用:
re.findall(r'^Title:\s(.+)$', text, re.S)
re.findall(r'^Title:\s(.+)$', text, re.DOTALL)

标签: pythonregex

解决方案


您可以将正则表达式与DOTALL标志一起使用,以允许您.匹配换行符 char :

re.findall('^Title:\s(.+)$', book, re.DOTALL)

输出 :

Le Morte D'Arthur, Volume I (of II)\n       King Arthur and of his Noble Knights of the Round Table

推荐阅读