import Foundation
let pattern = #"([\w-]+): (.+?)\\r\\n(?:([^:]+?)\\r\\n)?"#
let regex = try! NSRegularExpression(pattern: pattern)
let testString = #"""
MIME-Version: 1.0\r\n
x-no-auto-attachment: 1\r\n
Received: by 10.200.36.132; Sun, 5 Feb 2017 01:21:33 -0800 (PST)\r\n
Date: Sun, 5 Feb 2017 01:21:33 -0800\r\n
Message-ID: <IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII@mail.gmail.com>\r\n
Subject: =?UTF-8?Q?MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM?=\r\n
=?UTF-8?Q?ail?=\r\n \
From: =?UTF-8?B?VGhlIGZ1Y2sgYXJlIHUgbG9va2luZyBmb3I/?= <noreply@mail.com>\r\n
To: mail mail <mail@mail.com>\r\n
Content-Type: multipart/alternative; boundary=1a3xca651sv561fd321c5xv61sd12\r\n
"""#
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