import Foundation
let pattern = #"^[A|C][1-9|A-HJ-PR-UW-Y][0-9][1-9|A-C][1-9|A-HJ-PR-UW-Y][0-9|A-HJ-PR-UW-Y]{3}[A-HJ-PR-UW-Y]{2}"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"""
A131K062CE04
A131K062CA04
A131K062CA
A131K062CE
A131K062CE
AZ31K062CE04
A136P099BH
A136Q09YBK
A136S02QCE
A136R09QAY
A136F04QBV
A136F08QAB
C136Q03UAU
A136D05BCG
A136B041AQ
"""#
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