abdur rahim abdur rahim - 1 month ago 6
Javascript Question

How to find everything inside a block except two case

How to capture Fruits from the following pattern given that it doesnot contain
mango or grapes inside it ?

input:

<frutis>banana,apple,orrange,lichie</frutis>
<frutis>banana,apple,mango,lichie</frutis>
<frutis>banana,grapes,orrange,lichie</frutis>
<frutis>banana,apple,orrange,guava</frutis>


output:
banana,apple,orrange,lichie
false
false
banana,apple,orrange,guava<

I have tried the following :

<frutis>([^mango|grapes]*)<\/frutis>

Answer

Try this:

<frutis>((?:(?!mango|grapes).)*)<\/frutis>

Source Code Here:

const regex = /<frutis>((?:(?!mango|grapes).)*)<\/frutis>/g;
const str = `<frutis>banana,apple,orrange,lichie</frutis>
<frutis>banana,apple,mango,lichie</frutis>
<frutis>banana,grapes,orrange,lichie</frutis>
<frutis>banana,apple,orrange,guava</frutis>`;
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}`);
    });
}

I have used negative look ahead to detect if that two strings exist or not. Full explanation can be found here