Is there a regex pattern to match titles in the following reStructuredText -like text ? The difficulty is that the numbers of equal signs must be equal to the length of the title.
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...
Search for match(es) of (?:^|\\n)(=+)\\r?\\n(?!=)([^\\n\\r]+)\\r?\\n(=+)(?:\\r?\\n|$)
. If match found, check if lengths of first, second and third groups are same. If so, title is a content of second group.
To support full syntax for section titles , you could use 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.