import Foundation
let pattern = #"\{.*\[type=(.*),\s*reason=(.*)],\s*data=.*\}"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"[10:58:56] [INFO] [cn.qstec.gateway.filter.es.DaptSaveOrUpdateResponseGatewayFilterFactory] [] [-] [-] [返回体===>{code=1, state=false, message=upsert failed index [cards_house_translation] type _doc id hr1811-116-IH Exception Elasticsearch exception [type=illegal_argument_exception, reason=Document contains at least one immense term in field="article_translation" (whose UTF8 encoding is longer than the max length 32766), all of which were skipped. Please correct the analyzer to not produce such terms. The prefix of the first immense term is: '[60, 104, 116, 109, 108, 32, 120, 109, 108, 110, 115, 58, 109, 115, 61, 34, 117, 114, 110, 58, 115, 99, 104, 101, 109, 97, 115, 45, 109, 105]...', original message: bytes can be at most 32766 in length; got 44979], data=}]"#
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