import Foundation
let pattern = #"(?:count=)(?P<G1>\d+(?=\.0, state=STATE_ONE))?(?P<G2>\d+(?=\.0, state=STATE_TWO))?(?P<G3>\d+(?=\.0, state=STATE_THREE))?(?P<G4>\d+(?=\.0, state=STATE_FOUR))?(?P<G5>\d+(?=\.0, state=STATE_FIVE))?(?P<G6>\d+(?=\.0, state=STATE_SIX))?(?P<G7>\d+(?=\.0, state=STATE_SEVEN))?(?P<G8>\d+(?=\.0, state=STATE_EIGHT))?(?P<G9>\d+(?=\.0, state=STATE_NINE))?(?P<G10>\d+(?=\.0, state=STATE_TEN))?(?P<G11>\d+(?=\.0, state=STATE_ELEVEN))?"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"xxx <xx>x 2020-02-07T18:57:21.980698+00:00 xxxxxx.prod.xxxx xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx [APP/PROC/WEB/0] - - 2020-02-07 18:57:21.980+0000 org{xxxxxxxx} INFO x.x.x.x.x.x.implementation.WorkflowAPI [] [] [] [{count=55.0, state=STATE_ONE}, {count=10.0, state=STATE_TWO}, {count=13.0, state=STATE_THREE}, {count=12.0, state=STATE_FOUR}, {count=11.0, state=STATE_FIVE}, {count=14.0, state=STATE_SIX}, {count=1.0, state=STATE_SEVEN}, {count=69.0, state=STATE_NINE}, {count=420.0, state=STATE_ELEVEN}]"#
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