import Foundation
let pattern = #"\<([^>]+)\>\s+([^<]*?)\s*(?=\<|$)"#
let regex = try! NSRegularExpression(pattern: pattern)
let testString = #"""
Jul 8 22:02:05 RXXXXXXX001 MCS:BS: <Code> 30900 <Type> WARNING <Severity> PROCESS <Category> APPLICATION <User> root <HwSource> RXXXXXXX001 <Summary> Activity failed
- timed out before completion. <Group> SQL_Transaction_Logs_4_Hours <Action> Scheduled Backup <status_code> 30900 <starttime> 2019-07-08 23:00:00 <targetCid> 8exxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx9 8xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx9 <account_name> rxxxxxxxxxxx.xx.xxxxxxx.com <client> /clients/rxxxxxxxxxxx.xx.xxxxxxx.com <bytes_modified_sent> 0 <client_name> rxxxxxxxxxxx.xx.xxxxxxx.com <errorcode> 10019 <CID> 8exxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx9 <hard_limit> 0 <retention_policy> 14_Days <bytes_protected> 0 <endtime> 2019-07-09 0 3:02:05 <PID> SQL <plugin_name> Windows SQL <snapup_number> <snapup_label> <schedule> Transaction log 4 HR <bytes_scanned> 1 <WID> Transaction log 4 HR-SQL_Transactio n_Logs_4_Hours-1562626800005 <domain> /clients <dataset> /Transactional_Log _4_Hours <account> /clients/rxxxxxxxxxxx.xx.xxxxxxx.com
"""#
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