python - 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', '')]
正确的方法应该是什么?
解决方案
您需要在这里使用re.MULTILINE
和re.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']
推荐阅读
- sql - 具有多个条件的 CASE - Teradata/SQL
- c++ - 调用函数时的向量后推调用析构函数
- python - 如何计算python中每一列中缺失的数据?
- javascript - 在 ngFor 中更新模型
- docker - 如何最小化只需要 git、cron 和 openjdk-8-jre 的 ubuntu docker 镜像
- javascript - 在 select2 输入搜索元素处添加自定义事件
- javascript - 推迟更新 DOM
- wordpress - 根目录“下方”的文件的正确路径是什么?
- wordpress - 使用简码遍历 WordPress 中的数组
- regex - Perl 字符串操作和查找