如何在laStructuredText中找到标题

时间:2013-12-01 13:09:05

标签: python regex python-3.x restructuredtext

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

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...

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分: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