import Foundation
let pattern = #".*?\((.*)%\)|^(\S+)\s\[.*"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"""
1991 (38.26%)
1018 (41.52%)
438 (35.12%)
771 (35.16%)
244 (35.72%)
343 (32.48%)
316 (40.51%)
177 (33.84%)
133 (41.18%)
792 (35.92%)
3190 (61.30%)
1426 (58.16%)
803 (64.39%)
1415 (64.52%)
436 (63.84%)
711 (67.33%)
463 (59.36%)
345 (65.97%)
187 (57.89%)
1403 (63.63%)
44.00 [38.00 - 50.00]
43.00 [37.00 - 49.00]
43.00 [37.00 - 49.00]
44.00 [38.00 - 50.00]
44.00 [39.00 - 50.00]
44.00 [38.00 - 50.00]
43.00 [37.00 - 49.00]
45.00 [39.00 - 51.00]
44.00 [37.00 - 50.00]
45.00 [38.00 - 51.00]
"""#
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