Regex section text extraction

Hello! I’m banging my head against a regex problem. Please help!

I have the contents of a markdown file. I want to, with regex, get the contents of a specific section without including the heading. I also want it to be possible that the heading is the last one in the file.

So with either:

# want
actual text that I want

# heading to skip
some irrelevant text

or

# heading to skip
first heading text

# want
actual text that I want

the result I want is actual text that I want.

after some trial and error it seems that my difficulty was in understanding the difference between greedy and lazy. Carry on!

In case anyone needs this later, it’s something like:

// text is the contents of the note
text += "\n# dummy" // couldn't work out how to extract a section if it was the last section, so this hack adds a dummy section
let arr = text.match(/(?<=\n# draft)[\w\W]*?(?=\n# )/g) || [""]
return arr[0] // return the match

Be advised that there is metadata cache which holds information on which lines are used for section headings, which potentially could simplify your efforts.

1 Like

thanks, I’ll give it a look!

EDIT: this rules, thanks for the tip!

for anyone finding this thread, here’s how I got started:
https://txt.binnyva.com/2021/08/metadata-frontmatter-of-current-note-in-obsidian/

1 Like

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.