【问题标题】:How to find title a la reStructuredText如何在 reStructuredText 中找到标题
【发布时间】:2013-12-17 05:24:27
【问题描述】:

是否有正则表达式模式来匹配以下reStructuredText-like 文本中的标题?困难在于等号的数量必须等于标题的长度。

Some basic text.


=========
One Title
=========

For titles the numbers of sign `=` must be equal to the length of the text title. 


============= 
Another title
============= 

And so on...

【问题讨论】:

  • 这不能在 python 的完整正则表达式中完成。您唯一能做的就是捕获三行中的每一行并检查之后的长度。
  • 您肯定需要回调。例如,匹配每个标题,然后检查长度。作为开始(?s)(={3,})\r?\n(.*?)\r?\n\1demo——比较第1组和第2组的长度。否则你会得到像“vertical” regex matching in an ASCII “image”这样的大型正则表达式,这在Python中不应该像@CasimiretHippolyte所说的那样。跨度>
  • .NET btw 中可行
  • @OGHaza 解释解释 *兴奋* :D
  • @HamZa, explanation - 它几乎不干净;)

标签: python regex python-3.x restructuredtext


【解决方案1】:

搜索(?:^|\n)(=+)\r?\n(?!=)([^\n\r]+)\r?\n(=+)(?:\r?\n|$) 的匹配项。如果找到匹配,检查第一组、第二组和第三组的长度是否相同。如果是这样,标题是第二组的内容。

【讨论】:

  • 回电并不是一个痛苦的约束,但我希望有更直接的东西。谢谢!
  • 检查长度:规范说“至少与标题文本一样长”,因此您可以测试 G2.length
  • @Jongware - 你在哪里读到“至少” ..?我没看到。
  • docutils.sourceforge.net/docs/ref/rst/…: “...从第 1 列开始,形成一条至少延伸到标题文本右边缘的线。”诚然,这取决于 OP 的精确程度正计划遵循规范。
  • 事后思考:.. 那些相同的规范建议使用(=+),而不是(([!"#$%=])\2*)(带有允许的字符的完整列表),但这又取决于OP的严格性。
【解决方案2】:

要支持full syntax for section titles,您可以使用docutils package

#!/usr/bin/env python3
"""
some text

=====
Title
=====
Subtitle
--------

Titles are underlined (or over- and underlined) with a printing
nonalphanumeric 7-bit ASCII character. Recommended choices are "``= -
` : ' " ~ ^ _ * + # < >``".  The underline/overline must be at least
as long as the title text.

A lone top-level (sub)section is lifted up to be the document's (sub)title.
"""
from docutils.core import publish_doctree

def section_title(node):
    """Whether `node` is a section title.

    Note: it DOES NOT include document title!
    """
    try:
        return node.parent.tagname == "section" and node.tagname == "title"
    except AttributeError:
        return None # not a section title

# get document tree
doctree = publish_doctree(__doc__)    
titles = doctree.traverse(condition=section_title)
print("\n".join([t.astext() for t in titles]))

输出:

Title
Subtitle

【讨论】:

  • 有趣。感谢您的提示。
  • @projetmbc:注意:Node 接口比许多任务要复杂得多。如果您想更紧密地使用文档树,我会先将其转换为 xml.etree.ElementTree(序列化为 xml/将其解析为 etree)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-01-13
  • 2011-01-22
  • 1970-01-01
  • 2021-08-29
  • 2013-10-04
  • 2023-03-27
  • 1970-01-01
相关资源
最近更新 更多