import Foundation
let pattern = #"\[(?P<timestamp>[\w-]+\s[\w:]+[+\.]\d+)\] \[(?P<level>\S+)\]\:(?P<bho>\s+)\t\{(?P<id>\d+)\} \[(?P<telefono>\S+)\] \[(?P<ip>\S+)\] (?P<node>\w*)\s*\[(?P<path>\S+)?\s\]\[(?P<bho2>\s\d+\s)\]\[\s(?P<id2>\d+\s)\]"#
let regex = try! NSRegularExpression(pattern: pattern)
let testString = #"""
[2020-05-22 12:49:09.1640] [info]: {2012} [393471039213] [10.8.19.191] MASTER [netmon.condiviso_368-pwc ][ 160239552803493 ][ 1292 ]
[2020-02-13 01:01:03.9170] [info]: {2} [393454639076] [10.8.4.218] MASTER [netmon.condiviso_368-pwc ][ 160130554375066 ][ 1855 ]
[2020-02-13 02:10:05.5750] [info]: {499} [393481505158] [10.8.17.5] [netmon.traffico.393481505158.10.8.17.5_371-pwc ][ 4880942571 ][ 16274 ]
"""#
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