refactor: read the heading level without a regex

mypy saw re.fullmatch() as optional. Splitting the hashes off the heading gives the same level and title.
This commit is contained in:
Abdessamad Derraz committed 2026-11-21 06:04:40 +01:00
1 parent d73afff852
commit 13db912e52
1 file changed
+3 -1
+3 -1
View File
@@ -19,7 +19,9 @@ def section(text: str, heading: str, *, stop: int | None = None) -> str:
The heading is its text, or the full line with its hashes, which then
fix its level; a trailing ``{ #anchor }`` is optional either way."""
hashes, title = re.fullmatch(r"(#*)\s*(.*)", heading).groups()
title = heading.lstrip("#")
hashes = heading[: len(heading) - len(title)]
title = title.strip()
start = re.search(rf"(?m)^({hashes or '#+'}) {re.escape(title)}(?:\s*\{{[^}}]*\}})?\n", text)
if start is None:
raise AssertionError(f"no section {heading!r}")