import Foundation
let pattern = #"Timestamp: (?<datetime>.+)[\r\n]+Message: (?<msg>[\s\S]*)[\r\n]+Category: (?<unparsed1>[\s\S]*)Machine: (?<instance>.*)[\r\n]+(?<unparsed2>[\s\S]+)"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"Timestamp: 10/06/2023 23:59:56.2329081 Message: Requests has exceeded the rate limit of 100/Minute. There were a total of 140 requests for clientId 'eb9f3c62-d0a5-4234-8dc0-ad6700d58eff' from IP '123.456.789.012' on endpoint '/Whatever/api/v1/blah'. Time period started at 10/6/2023 11:59:23 PM and request was blocked at 10/6/2023 11:59:56 PM next line next line Category: Whatever EventId: 43122 Severity: Information Title: Machine: i-0ce037c69c9df1e33 Application Domain: /LM/W3SVC/1/ROOT/Whatever-1-133410567318541375 Process Id: 3860 Process Name: c:\windows\system32\inetsrv\w3wp.exe Win32 Thread Id: 2444 Thread Name: Extended Properties: "#
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