const regex = /(\S*) && (\1[\.\[]).+/gm;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('(\\S*) && (\\1[\\.\\[]).+', 'gm')
const str = `// Optional chaining for Javascript is now in stage 4:
// https://github.com/tc39/proposal-optional-chaining
// WARNING: This is NOT native to JS yet, so you will need to use a babel plugin to convert it:
// https://babeljs.io/docs/en/babel-plugin-proposal-optional-chaining
// Which means you can use this regex to find where in your codebase you can replace this:
user && user.profile && user.profile.email
// with this:
user?.profile?.email
// these should match because they have an object variable being accessed multiple times with a dot or opening bracket
data && data[query] && data[query].items && data[query].items.length > 0
const street = user.address && user.address.street;
// this should not match because they're not accessing the same object
data && form.user && api.authenticated`;
// 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