const regex = /(<(?:[^ >]+|.+? (["'])?.+\2)>)/g;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('(<(?:[^ >]+|.+? (["\'])?.+\\2)>)', 'g')
const str = ` <foo><!foo1> 1
<foo2 bar> 2
<!foo3 bar=baz> 3
<foo4 bar="baz"> 4
<!foo5 bar='baz'> 5
<foo6 bar=baz baz="bar"> 6
<!foo7 bar="baz" baz='bar'> 7
<foo8 bar='<baz>'> 8
<!foo9 bar='<foo>' baz='<bar><baz>'> 9
<foo10 'bar'>10</foo10>
<foo11 "bar">11</foo11>
<foo12 '<bar>'>12</foo12>
<foo13 "foo<bar><baz>">13</foo13>
<foo14 "<foo bar='baz'>">foo14</foo14>
<foo15><foo16>foobar</foo16></foo15>
`;
// 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