Text Extraction
Markdown Heading Regex
ATX headings in Markdown start with one to six hash marks followed by a space. This pattern anchors at the start of a line using the m flag, captures the hashes in group 1 so the heading level equals its length, requires at least one whitespace character, and captures the heading text in group 2. It is a quick way to build a table of contents, check that a document does not skip levels, or extract section titles for search. Lines like #hashtag are skipped because they lack the space, and seven hashes are rejected because Markdown defines only six levels.
Pattern (JavaScript)
/^(#{1,6})\s+(.+)$/mStarts at the start of the line/string, then a group (the character "#", between 1 and 6 times), then one or more whitespace characters, then a group (any character, one or more times), then the end of the line/string.
Examples
Matches
- ✓ # Title
- ✓ ### Section three
- ✓ intro ## Next part
Does not match
- ✗ #hashtag
- ✗ ####### seven
- ✗ text # not heading
Try it
3 matches (JavaScript engine)
# Title ### Section three intro ## Next part #hashtag ####### seven text # not heading
Code in 8 languages
Converted automatically from the JavaScript pattern; language-specific notes are shown where the syntax or support differs.
JavaScript
const re = /^(#{1,6})\s+(.+)$/gm;
const text = "# Title";
const matches = [...text.matchAll(re)].map((m) => m[0]);
console.log(matches);Python
import re
pattern = re.compile(r'^(#{1,6})\s+(.+)$', re.M)
text = '# Title'
matches = [m.group(0) for m in pattern.finditer(text)]
print(matches)PHP
<?php
$pattern = '/^(#{1,6})\s+(.+)$/m';
$text = '# Title';
preg_match_all($pattern, $text, $matches);
print_r($matches[0]);Java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("^(#{1,6})\\s+(.+)$", Pattern.MULTILINE);
String text = "# Title";
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
System.out.println(matcher.group());
}
}
}Go
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`(?m)^(#{1,6})\s+(.+)$`)
text := "# Title"
fmt.Println(re.FindAllString(text, -1))
}C#
using System;
using System.Text.RegularExpressions;
var pattern = new Regex(@"^(#{1,6})\s+(.+)$", RegexOptions.Multiline);
var text = "# Title";
foreach (Match m in pattern.Matches(text))
{
Console.WriteLine(m.Value);
}Rust
// Cargo.toml: regex = "1"
use regex::Regex;
fn main() {
let re = Regex::new(r"(?m)^(#{1,6})\s+(.+)$").unwrap();
let text = "# Title";
for m in re.find_iter(text) {
println!("{}", m.as_str());
}
}- Add regex = "1" under [dependencies] in Cargo.toml.
Ruby
pattern = /^(\#{1,6})\s+(.+)$/
text = '# Title'
matches = text.to_enum(:scan, pattern).map { Regexp.last_match[0] }
p matches- Flag(s) m not available in this language and were left out.
Frequently asked questions
- How do I get the heading level as a number?
- Read the length of group 1. One hash is level 1, two hashes are level 2, and so on up to six.
- Does this match underlined Setext headings?
- No. Setext headings use a line of = or - characters under the text, which needs a two-line pattern. This one covers the hash style only.
- Will it match hash lines inside code blocks?
- Yes, because a regex cannot see fenced code block context. Strip or skip fenced blocks first if your documents contain shell comments or code samples.