Hello,
The attached macro should if it worked extract only the lines which start with # (hashtag followed by space, which represents level 1 headers in Bear markdown notes). End of header is a line feed (hard return). I would like the resulting title to be separated by a blank line.
I think that something is wrong with the regular expression.
THANKS VERY MUCH !
——————————————————————————
The test text is
testing title this is a test using a title
Hello,
Text format is Markdown (Bear).
testing level 2 header
the title line ends with a new line feed
if possible, I would like to insert a blank line between extracted titles (the list of titles), to make the list more readable.
3rd level header
another title
and some text
a third title
another paragraph header
——————————————————————————
and the end results should
testing title this is a test using a title
another title
a third title
——————————————————————————
The KM Error message in the engine log file is:
2023-11-29 13:37:02 Search Regular Expression failed to match ^# .*. Macro “Trying” cancelled (while executing Search Text “# testing title…” Using Regular Expression (ignoring case)).
——————————————————————————
Yes - the Search action finds only the first match.
As the KM wiki says:
"Note: This RegEx Search returns only the first match in the source text.\
If you want to process all matches, you will need to use a [[action:For_Each|For Each Action]] as [[:Regular_Expressions#Examples|Shown in this Example]]."
Oooh, a chance to demonstrate two of my fave KM/regex features :).
You can actually do this all in one pass by finding what doesn't match the data you want to keep and removing it. (I got very good at this with an early version of my Quick Web Search macro, before it switched to using a database—I had to often extract a few things from a long list, and this was the fastest way to do it.)
That find part uses two cool regex features. The first is the (?m) bit, which means "multiline," so it will apply the regex to all lines, one by one. Then there's the second regex feature, a negative lookahead:
(?!# ) This means "only match what follows if it is not preceded by a #-space combo." That is then followed by .*$, which means "everything else until the end of the line." Rephrased, this regex finds everything on all lines that do not start with a "pound space."
The replace is then blank, that is, we replace anything that doesn't match with nothing at all. That leaves just one step, a simple regex to remove the blank lines. At the end, the var contains only the headlines.
It's a weird construct, but it is oh so incredibly useful for parsing multi-line variables and getting what you want without having to loop through them line by line.
Fantastic macros which approach the problem from 2 different angles. Many thanks to both of you @tiffle and @griffman . I will make favorite actions out of your macros