const regex = /(?:^|\n\n)From .*?(?:\nSubject: )([^\n]*End of shift.*?\n).*?\n\n(.*?)(?=\n\nFrom |$)/gs;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('(?:^|\\n\\n)From .*?(?:\\nSubject: )([^\\n]*End of shift.*?\\n).*?\\n\\n(.*?)(?=\\n\\nFrom |$)', 'gs')
const str = `From MAILER-DAEMON Fri Jul 8 12:08:34 2011
From: Author <author@example.com>
To: Recipient <recipient@example.com>
Subject: Sample message 1
This is the body.
>From (should be escaped).
There are 3 lines.
From MAILER-DAEMON Fri Jul 8 12:08:34 2011
From: Author <author@example.com>
To: Recipient <recipient@example.com>
Subject: Sample message End of shift 2
Other Headers: useless stuff
This is the second body.
Stuff
TECH
From MAILER-DAEMON Fri Jul 8 12:08:34 2011
From: Author <author@example.com>
To: Recipient <recipient@example.com>
Subject: Sample message 2
Precedence: bulk
X-No-Archive: yes
MIME-Version: 1.0
This is the third body.
From MAILER-DAEMON Fri Jul 8 12:08:34 2011
From: Author <author@example.com>
To: Recipient <recipient@example.com>
Subject: End of shift Sample message 2
Precedence: bulk
X-No-Archive: yes
MIME-Version: 1.0
This is the forth test.
This is the body.
>From (should be escaped).
There are 4 lights.
Lots of text
TECH
From MAILER-DAEMON Fri Jul 8 12:08:34 2011
From: Author <author@example.com>
To: Recipient <recipient@example.com>
Subject: Sample message 4
Precedence: bulk
X-No-Archive: yes
MIME-Version: 1.0
This email is the fifth email
TECH
`;
// 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