Okay, I've experimented and this is what I've found:
The JXA provided by @JMichaelTX works nicely; however, it is a little bit slow when the script is called many times within the same macro (as, in practice, my macro will need to do).
The native KM/regex solution provided by @ccstone is far snappier and therefore preferable in this respect. The only problem is that does not work across line breaks.
I should share my real use case at this point, rather than the simplified example I gave initially.
In short, my objective is to take markdown text that contains reference information delimited by backticks and put each backtick-delimited substring into a unique footnote. In other words, it is converting an in-line citation style into a footnote (or endnote) style, within markdown.
So, this is what I have:
Convert backtick-delimited citations to footnotes [TEST].kmmacros (8.1 KB)
The output of the above macro, at present, is this:
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua [^fn1]. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat [^fn2].
Ut enim ad minim veniam `[Jessop, 2011, #16381]`, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua `[Rogers, 2018, #4879; Ruiz, 1976, #29023]`. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
[^fn1]: [Jessop, 2011, #16381]
[^fn2]: [Jessop, 2011, #16381]
[^fn3]: [Jessop, 2011, #16381]
[^fn4]: [Rogers, 2018, #4879; Ruiz, 1976, #29023]
So, as you can see, the macro replaces the first two citations correctly but stops at the first paragraph.
You can also now see why I need to search and replace only the first instance of each substring. If I used the standard Search and Replace, all three instances of "[Jessop, 2011, #16381]" would become "[^fn1]". (N.B. There are citation styles where this would be correct but these styles are not used within my field.)
In any case, I've been learning some regex recently but this goes beyond my limited understanding! Pointers and corrections all appreciated.
P.S. the other problem with my current macro is that it needs to place the in-line [^fn#]
marker to the right of the .
or ,
not to the left (it will become superscript when exported to rich text). However, that should be easy to fix once the main problem is resolved.