const regex = /^([A-Za-z \t]*)```([A-Za-z]*)?\n([\s\S]*?)```([A-Za-z \t]*)*$/gm;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('^([A-Za-z \\t]*)```([A-Za-z]*)?\\n([\\s\\S]*?)```([A-Za-z \\t]*)*$', 'gm')
const str = `Markdowndown code blocks work with triple \`'s
This pattern matches prefix, syntax, contents, and postfix
Like this \`\\\`\\\`\\\`\` or "\`\`\`" or \`\`\` inline blocks are like this \`code here\`
x\`\`\`js
asdf
\`\`\`
\`\`\`
test
\`\`\`
Indented
\`\`\`
test
\`\`\`
\`\`\`js
xyz
\`\`\`
Indented with syntax
\`\`\`js
xyz
\`\`\`
With code content
\`\`\`js
const foo = () => {}
\`\`\`
Postfix
\`\`\`js
const foo = () => {}
\`\`\`x
With internal ticks
\`\`\`js
// comment \`
const foo = \`lol
cool with ticks \\\`\\\`\\\`
\`
\`\`\``;
// 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