const regex = /(<item>[^<]*?<title>(?<title>[^<]*?)<\/title>([^<]|<(?!description))*<description>(?<desc>[^<]*?keyword[^<]*?)<\/description>[^<]*?<\/item>)/gs;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('(<item>[^<]*?<title>(?<title>[^<]*?)<\\\/title>([^<]|<(?!description))*<description>(?<desc>[^<]*?keyword[^<]*?)<\\\/description>[^<]*?<\\\/item>)', 'gs')
const str = `<item>
<title>bla</title>
...
<description>bla</description>
</item>
<item>
<title>bla2</title>
<summary>bla2</summary>
<summary>bla2</summary>
<summary>bla2</summary>
<description>bla2, keyword here are blablabla</description>
</item>
<item>
<title>bla2</title>
....
<description>no kword here</description>
</item>
blablabla
<item>
<title>bla</title>
...
<description>bla</description>
</item>
<item>
<title>bla2</title>
<summary>bla2</summary>
<description>bla2, keyword here are blablabla</description>
</item>
<item>
<title>bla2</title>
<summary>bla2</summary>
<description>bla2, keyword here are blablabla</description>
</item>`;
// 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