首页 > 解决方案 > Python 正则表达式 findall 点 + 换行符

问题描述

我正在尝试使用 Python 提取包含某个字符串的段落。例子:

text = """test textract.

new line
test word.

another line."""

以下代码有效:

myword = ("word")
re.findall(r'(?<=(\n)).*?'+ myword + r'+.*?(?=(\n))',text)

并将返回:

['test word.']

但是,如果我想提取 ['new line test word.'],以下都不起作用:

re.findall(r'(?<=(\.\n)).*?'+ myword + r'+.*?(?=(\.\n))',text) -> []
re.findall(r'(?<=(\.\n)).|\n*?'+ myword + r'+.|\n*?(?=(\.\n))',text) -> [('', '.\n'), ('', '.\n')]
re.findall(r'(?<=(\.\n)).*|\n*?'+ myword + r'+.*|\n*?(?=(\.\n))',text) -> [('', '.\n'), ('.\n', ''), ('', '.\n'), ('.\n', '')]

正确的方法应该是什么?

标签: pythonregex

解决方案


您需要在这里使用re.MULTILINEre.DOTALL将整个文本分析为单行,并将换行符视为常规字符:

import re

text = """\
test textract.

new line
test word.

another line."""

print(re.findall(r'\n+(.*word.*)\n+', text, re.MULTILINE | re.DOTALL))

输出:

['new line\ntest word.\n']

推荐阅读