const regex = /(?:^|\n)##\s[^\n]*\n(.*?)(?=\n##?\s|$)/gs;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('(?:^|\\n)##\\s[^\\n]*\\n(.*?)(?=\\n##?\\s|$)', 'gs')
const str = `# This is an H1
content
content
content
## This is an H2 that ends in another H2
matched content 1
matched content 1
matched content 1
## This is an H2 that ends in an H1
matched content 2
matched content 2
matched content 2
# This is an H1, it's content doesn't belong to any H2
content
content
content
## This is an H2 that goes on until the end of the file
matched content 3
matched content 3
### This H3 belongs to the H2 above
matched content 4
matched content 4`;
// Reset `lastIndex` if this regex is defined globally
// regex.lastIndex = 0;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for JavaScript, please visit: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions