const regex = /(\bShe\b)(?:(?!\b(?:she|loves|you)\b).)*(\bloves\b)(?:(?!\b(?:she|loves|you)\b).)*(\byou\b)/gmi;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('(\\bShe\\b)(?:(?!\\b(?:she|loves|you)\\b).)*(\\bloves\\b)(?:(?!\\b(?:she|loves|you)\\b).)*(\\byou\\b)', 'gmi')
const str = `My she baby loves loving, my baby loves loving She's got what it takes, and she knows how to use it My baby loves loving, my baby loves loving She's got what it takes, and she knows how to use it I was lonely once in this great big world Just a nowhere man without a girl 'Till that lucky day when she came my way And she smiled at me as if to say My baby loves loving, my baby loves loving She's got what it takes, and she knows how to use it My baby loves loving, my baby loves loving She's got what it takes, and she knows how to use it She's the only one, makes me feel so good Can't believe my love so I knock on wood All my silent fears seem to fly away And she smiled at me as if to say Your baby loves loving, my baby loves loving She's got what it takes for me No more lonely nights just waiting for the telephone to ring No more lonely days, my baby's taking care of everything I'm telling you people My baby loves loving, my baby loves loving She's got what it takes, and she knows how to use it My baby loves loving, my baby loves loving She's got what it takes, and she knows how to use it She's the only one, makes me feel so good Can't believe my love so I knock on wood All my silent fears seem to fly away And she looked at me as if to say`;
// 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