const regex = /(\${1,2})[^]*?[^\\]\1|[^\$]+/g;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('(\\${1,2})[^]*?[^\\\\]\\1|[^\\$]+', 'g')
const str = `some text outside \$ \\\$2+\\\$ \$ which includes \$\\\$\$
Now some \$\${}\$\$ \$\\{\\}\$inline mathjax \$2+2\$
And in new lines
\$\$
2+2
\$\$
\$
2+2\\\\
3+3\\\\
4+4\\\\
\$
more inline \$2+2\\\$ \\\$2+2\$ \$2+2\$, \$3+4\$
separated \$2+2\$ by some text \$ 2+2 \$ again
double newlines
\$2+2\$
\$2+2\$
Dollar again \$ \\\$42 \$
\$\$ \\\$42 \$\$
\$\$
\\frac{4}{2}+
\\frac{4}{2}
\$\$
And some more tests:
\\> a) \$\\dr{1}{2}+\\left(\\dr23-\\dr34\\right)\$<<<
\\> b) \$\\dr{1}{5}+\\left(\\dr23-\\dr12\\right)\$<<<
\\> c) \$\\dr{1}{2}+\\left(\\dr{3}{4}-\\dr32\\right)\$<<<
\\> d) \$\\left(\\dr{3}{10}-\\dr{5}{2}\\right)+\\dr7{20}\$<<<
\\> e) \$\\dr{2}{3}+\\left(\\dr{3}{2}-\\dr14\\right)\$<<<
\\> f) \$\\left(\\dr{14}{5}-\\dr7{10}\\right)+\\dr{11}{10}\$.<<<
\$\$
a^{\\rr mn}=\\sq[n]{a^m}.
\$\$
\$\$
\\begin{align}
&a^x\\cdot a^y=a^{x+y}\\\\
&\\dr{a^x}{a^y}=a^{x-y}\\\\
&(a^x)^y=a^{xy}\\\\
&(ab)^x=a^xb^x\\\\
&\\left(\\dr ab\\right)^x=\\dr{a^x}{b^x}.
\\end{align}
\$\$
\$\$
\\sq[4]{5\\sq5}=(5\\sq5)^{\\rr14}=(5\\.5^{\\rr12})^{\\rr14}=
(5^{1+\\rr12})^{\\rr14}=(5^{\\rr32})^{\\rr14}=5^{\\rr38}.
\$\$
Hope that's it.
`;
// 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