Skip to content

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.

Pattern flags: gm
^(#{1,6})\s+(.+)$
Test this pattern in the Regex Tester →

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

Match
# Main Title
Matches: # Main Title
Match
### Sub Section
Matches: ### Sub Section
No Match
Not a heading

Common Uses

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.

Related Patterns

Markdown Link

\[([^\]]+)\]\(([^)]+)\)

HTML Tag

<\/?([a-zA-Z][a-zA-Z0-9]*)\b[^>]*>

Related Reading

Regex Cheat Sheet with Examples for Developers → URL Encoding Special Characters →