python - 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)
解决方案
您可以将正则表达式与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
推荐阅读
- javascript - 单击 ReactJs 中的 Switch Name 按钮后没有得到正确的输出
- scala - 如何使日期的年数和周数对齐
- reactjs - 如何在不改变状态的情况下重新渲染组件
- docker - docker 容器中的 DNS 解析
- c# - 如何在 dotnet core razor pages (3.1) 中打开新创建的 Model Razor Page
- python - 将一列中的json数据传播到多列
- c# - 如何使用字典映射类型和操作以自动转换值?
- r - 生存包的 coxph() 函数中的“termlabels”错误
- tsql - CASE 函数顺序 - T - SQL
- python - np.concatenate:它对单个 ndarray 作为输入有什么作用