首页 > 解决方案 > 在python中匹配单词到单词的内容

问题描述

我想正则表达式从 python 列表中的内容,

内容是这样的:

garbage text
garbage text
Heading 1:
  important content abx
  important content xvy
  important content
  important content xyz
  important content zed
Heading 2:
 more content

我想将内容从“标题 1”抓取到“zed”

我已经尝试过的事情:

regex = r'Heading 1.*?zed'

但它不适用于多行

标签: pythonregex

解决方案


尝试re.findall在全点模式下使用以下模式:

\bHeading 1:.*?(?=Heading \d+|$)

全部点模式将确保跨行.*?匹配。结尾的前瞻将在下一个标题开始之前或输入结束之前停止,以先发生者为准。

示例脚本:

inp = """garbage text
garbage text
Heading 1:
  important content abx
  important content xvy
  important content
  important content xyz
  important content zed
Heading 2:
 more content"""

matches = re.findall(r'\bHeading 1:.*?(?=Heading \d+|$)', inp, flags=re.DOTALL)
print(matches[0])

这打印:

Heading 1:
  important content abx
  important content xvy
  important content
  important content xyz
  important content zed

推荐阅读