Markdown Heading
Matches markdown ATX-style headings (# through ######).
Try it in RegexPro →Available in
JavaScript / ECMAScript code
const re = new RegExp("^(#{1,6})\\s+(.+)$", "gm");
const input = "# Title\n## Subtitle\n### Section";
const matches = [...input.matchAll(re)];
console.log(matches.map(m => m[0]));Uses `String.prototype.matchAll` for global iteration (Node 12+ / all modern browsers).
Python (re) code
import re
pattern = re.compile(r"^(#{1,6})\s+(.+)$", re.MULTILINE)
input_text = "# Title\n## Subtitle\n### Section"
for m in pattern.finditer(input_text):
print(m.group(0))Stdlib `re` module — no third-party dependency. Works on Python 3.6+.
Go (RE2) code
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`(?m)^(#{1,6})\s+(.+)$`)
input := `# Title
## Subtitle
### Section`
for _, match := range re.FindAllString(input, -1) {
fmt.Println(match)
}
}Uses `regexp.MustCompile` (panics on bad patterns at startup) and `FindAllString` for all matches.
Pattern
^(#{1,6})\s+(.+)$ (flags: gm)Raw source: ^(#{1,6})\s+(.+)$
How it works
Examples
Input
# Title
## Subtitle
### SectionMatches
# Title## Subtitle### Section
Input
####### Not a headingNo match
—Common use cases
- •Markdown parsers
- •Table-of-contents generators
- •Static site generators
Related patterns
Markdown Image
Text ProcessingMatches Markdown image syntax .
Markdown Link
Text ProcessingMatch Markdown links [link text](url) and capture both the display text and the URL.
C-Style Block Comment
Text ProcessingMatch C-style /* ... */ block comments across multiple lines.
Keep-a-Changelog Entry Header
Text ProcessingMatch Keep-a-Changelog style version headers like `## [1.2.3] - 2024-01-15` or `## 2.0.0`.
Related concepts
Lazy vs. Greedy Quantifiers
ConceptGreedy quantifiers (*, +) consume as much as possible before backtracking. Lazy quantifiers (*?, +?) consume as little as possible.
Capturing Groups and Non-Capturing Groups
ConceptParentheses group tokens and capture the matched substring. (?:...) groups without capturing — use it when you want grouping for quantifiers or alternation but don't need the submatch.
How to Match Across Newlines in JavaScript
How-toThe dot doesn't match newlines by default. Use the s (dotall) flag, or build an explicit [\s\S] alternative for engines that predate s.