import Foundation
let pattern = #"(?:^|\n\n)From .*?(?:\nSubject: )([^\n]*End of shift.*?\n).*?\n\n(.*?)(?=\n\nFrom |$)"#
let regex = try! NSRegularExpression(pattern: pattern, options: .dotMatchesLineSeparators)
let testString = #"""
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
"""#
let stringRange = NSRange(location: 0, length: testString.utf16.count)
let matches = regex.matches(in: testString, range: stringRange)
var result: [[String]] = []
for match in matches {
var groups: [String] = []
for rangeIndex in 1 ..< match.numberOfRanges {
let nsRange = match.range(at: rangeIndex)
guard !NSEqualRanges(nsRange, NSMakeRange(NSNotFound, 0)) else { continue }
let string = (testString as NSString).substring(with: nsRange)
groups.append(string)
}
if !groups.isEmpty {
result.append(groups)
}
}
print(result)
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 Swift 5.2, please visit: https://developer.apple.com/documentation/foundation/nsregularexpression