import Foundation
let pattern = #"(?P<timestamp>[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}.[0-9]{3}-[0-9]{4}) (?P<severity>[A-Z]) (?P<component>[A-Z]+) ?\[ ?(?P<context>[a-zA-Z0-9 ]+)] (?<message>[^\n]+)"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"""
MongoDB
2014-11-03T18:28:32.450-0500 I NETWORK [initandlisten] waiting for connections on port 27017
2019-04-09T14:03:15.546-0400 I COMMAND [conn1] command test.items appName: "MongoDB Shell" command: aggregate { aggregate: "items", pipeline: [ { $match: { a: { $gte: 4.0 } } } ], cursor: {}, lsid: { id: UUID("042b423f-91bb-43bd-a378-4657ad4e0b35") }, $db: "test" } planSummary: COLLSCAN cursorid:7185821004643502676 keysExamined:0 docsExamined:25000 hasSortStage:1 numYields:289 nreturned:101 reslen:1305014 locks:{ Global: { acquireCount: { r: 387 } }, Database: { acquireCount: { r: 387 } }, Collection: { acquireCount: { r: 387 } } } storage:{ data: { bytesRead: 6808584, timeReadingMicros: 4336 } } protocol:op_msg 34439ms
2014-11-03T18:28:32.450-0500
"""#
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