【发布时间】:2018-12-15 10:00:58
【问题描述】:
我有一个指定的正文块,其中包含一个 GitHub Markdown 列表,格式如下:
**HEADERONE**
- [x] Logged In
- [ ] Logged Out
- [x] Spun Around
- [x] Did the hokey pokey
但该列表被其他类似这样的垃圾包围:
A body paragraph about other things. Lorem ipsom and all that
**HEADERONE**
- [x] Logged In
- [ ] Logged Out
- [x] Spun Around
- [x] Did the hokey pokey
Maybe a link here www.go_ogle.com
Another list that isn't important
- [ ] Thing one
- [ ] Thing two
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
我可以在抓取后以编程方式截断字符串,但我很好奇是否有一种非常干净的方式来抓取我的列表?标题总是相同的,所以从**HEADERONE** 抓取直到双新行的第一个实例可以正常工作。不过,从**HEADERONE** 抓取到最后一行末尾的- [ 会很棒。
我正在使用
\*\*HEADERONE\*\*[^*]*?(?=\n{2})
虽然这在 regex101 中有效,但 re.search("\*\*HEADERONE\*\*[^*]*?(?=\n{2})",body) 出于某种原因不返回任何内容。
所以我把它改成
\*\*HEADERONE\*\*[\S\s]*?(?=\n{2})
但这太多了,包括第二个列表。有什么想法吗?
【问题讨论】:
-
有 CRLF 结尾吗?尝试将
(?=\n{2})替换为(?=(?:\r\n){2})。替代方案可以是(?m)^\*\*HEADERONE\*\*(?:\r?\n-\s*\[[^][]*].*)* -
试试
(?m)\*\*HEADERONE\*\*(?:\s+^- +\[.*)+。在此处查看现场演示regex101.com/r/A8gahu/1 -
@WiktorStribiżew 用
(?=(?:\r\n){2})替换(?=\n{2})效果很好!虽然它停止在 regex101 上工作,但它在 python3 中运行良好。如果您可以回答解释第二个字符串的不同之处或原因,我将标记为已接受! -
我还添加了一种非正则表达式方法来获取文本中的所有匹配项。
标签: python regex string python-3.x substring