extractSectionByHeading function
Extracts text under first heading matching headingPattern (e.g. r'^#\s+Install').
Audited: 2026-06-12 11:26 EDT
Implementation
String? extractSectionByHeading(String markdown, RegExp headingPattern) {
final List<String> lines = markdown.split('\n');
// Find the matching heading; the section body starts on the line after it.
final int heading = lines.indexWhere(headingPattern.hasMatch);
// No matching heading means there is no section to extract.
if (heading < 0) return null;
final int start = heading + 1;
// Collect lines until the NEXT heading (any line starting with '#'), which
// bounds the section. An all-whitespace body is treated as no section (null).
final List<String> out = <String>[];
for (int i = start; i < lines.length; i++) {
if (lines[i].trimLeft().startsWith('#')) break;
out.add(lines[i]);
}
return out.join('\n').trim().isEmpty ? null : out.join('\n').trim();
}