import Foundation
let pattern = #"^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} \S+ \(\S+\) - flush done sketch={flushed=(\d+) total=(\d+) pruned=(\d+)} num_org_metric=\d+ since_ms=(\d+)ms dt=[-+]?([0-9]*(\.[0-9]*)?[a-z]+)+"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"""
2018-03-05 22:52:52 INFO (app.go:391) - flush done sketch={flushed=264557 total=57979680 pruned=295} num_org_metric=448 since_ms=10964ms dt=2.2392s
2018-03-05 22:53:01 INFO (app.go:391) - flush done sketch={flushed=171045 total=57954960 pruned=253} num_org_metric=448 since_ms=9377ms dt=1.616403s
2018-03-05 22:53:10 INFO (app.go:391) - flush done sketch={flushed=190064 total=57933000 pruned=297} num_org_metric=448 since_ms=9366ms dt=982.968ms
2018-03-05 22:53:20 INFO (app.go:391) - flush done sketch={flushed=153243 total=57932520 pruned=89} num_org_metric=448 since_ms=9908ms dt=891.573ms
"""#
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