Regex for Markdown Heading
This regex matches Markdown ATX-style headings from H1 (one #) through H6 (six #). It captures the heading level indicators and the heading text separately. The multiline flag allows it to match headings on any line in a document. Markdown headings are used in documentation, README files, and content management systems for document structure.
^(#{1,6})\s+(.+)$ What is the regex pattern for Markdown Heading?
The regex pattern for Markdown Heading is ^(#{1,6})\s+(.+)$ with the gm flags. This regex matches Markdown ATX-style headings from H1 (one #) through H6 (six #). It captures the heading level indicators and the heading text separately. The multiline flag allows it to match headings on any line in a document. Markdown headings are used in documentation, README files, and content management systems for document structure. This pattern is commonly used for table of contents generation and document structure analysis.
Test Examples
# Main Title # Main Title ### Sub Section ### Sub Section Not a heading Common Uses
- ✓ Table of contents generation
- ✓ Document structure analysis
- ✓ Heading extraction
- ✓ Content outline creation
Variations
Specific level
^##\s+(.+)$ Matches only H2 headings
Setext-style
^(.+)\n([=-])+$ Matches underline-style headings (= for H1, - for H2)
With optional closing hashes
^(#{1,6})\s+(.+?)\s*#*$ Allows optional trailing # characters
Frequently Asked Questions
What are the two Markdown heading styles?
ATX-style uses # symbols (# H1 through ###### H6). Setext-style uses underlines: = for H1 and - for H2. ATX-style is more common and supports all six heading levels.
Why does the regex need the multiline flag?
The multiline flag (m) makes ^ and $ match the start and end of each line, not just the start and end of the entire string. This is essential because headings are line-based in Markdown.
How do I extract just the heading text?
The second capture group contains the heading text without the # symbols. In most regex implementations, access it via match[2] or the named group equivalent.