const regex = /(?=["'])"([^"\\\n]*(?:\\[\s\S][^"\\\n]*)*)[",.!]|'([^'\\\n]*(?:\\[\s\S][^'\\\n]*)*)[',.!]/gm;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('(?=["\'])"([^"\\\\\\n]*(?:\\\\[\\s\\S][^"\\\\\\n]*)*)[",.!]|\'([^\'\\\\\\n]*(?:\\\\[\\s\\S][^\'\\\\\\n]*)*)[\',.!]', 'gm')
const str = `"Then", he said, "we go home."
"My dear Lizzy,
"I wish you joy. If you love Mr. Darcy half as well as I do my dear Wickham, you must be very happy. It is a great comfort to have you so rich, and when you have nothing else to do, I hope you will think of us. I am sure Wickham would like a place at court very much, and I do not think we shall have quite money enough to live upon without some help. Any place would do, of about three or four hundred a year; but however, do not speak to Mr. Darcy about it, if you had rather not.
"Yours, etc."
"Hello World"
"Hey!Theererererzffzfzfzfz zfzfbcnhdzxghxhxhxhx"
Hello World!I am "Some random text"
"Hey There! This is Some Text!!!! which does not contain quotes.
"thefbjbbssbjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjcbsjcb cbcslablaffblafblbflabflbfabfalafbalbabfaflaflzbzbhavsjdjdbeblbvsbvskbv"
'Hello!!! This is single quoted example.'
'Hello!!!' This is single quoted example.'Here is the one.
`;
// 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