Simply use /(#{1,6}) *(\S ) *(?:\r|\n)*/
can indeed match the H1~H6 titles in Markdown. But it also matches the reference with the # (such as a comment) in the code block, such as:
A paragraph of text
Comments using >
or
# 使用四个空格缩进的注释
# Comments using `
// code... # 代码注释
# 使用"的注释
How to exclude these situations that do not require matching?
As far as your question is concerned.
/^#/
seems to be able to meet the needs, but it cannot support languages annotated with # such as php and bash.So if you want to be accurate enough, you need to parse md into chunks.
I think your question is that the rules for commented code blocks and titles are the same, how to distinguish them.
Two ways to distinguish
Title changing rules
Code blocks are placed in fixed tags