import Foundation
let pattern = #"([0-9]{3})([0-9]{3})(G|M|R|T{1})([0-9]{1,4}|[0-9]{1,3}K{0,1})(-)([0-9]{1,4}|[0-9]{1,3}K{0,1})(CM|FT|HM|HF|IN|KF|KM|MM|M|NM|SM|YD{1,2})"#
let regex = try! NSRegularExpression(pattern: pattern)
let testString = #"""
//Good Data
123345T1234-5678KM
000001T1234-5678KM
001001T1234-5678KM
011001T1234-567KM
011011T1234-567KM
011111T1234-567KM
123345T123-5678KM
123345T123-567KM
123345T123-56KM
123345T12-56KM
123345T12-5KM
123345T1-5KM
123345T1234-567KM
123345T1234-567HF
123345T1234-567SM
123345T123-5678KM
123345T1234-567KKM
123345T123-567KKM
123345T123-567KHF
123345T123-567KSM
123345T123-56KKM
123345T12-56KKM
123345T12-5KKM
123345T12-5KKM
123345T1-5KKM
000359T1234-5678KM
123345T123K-5678KM
123345T12K-5678KM
123345T6K-5678KM
123345T123K-567KKM
123345T12K-56KKM
123345T6K-5KKM
123345T1234-5678M
//Bad Data
1234567T1234-5678KM
12345T1234-5678KM
1245T1234-5678KM
145T1234-5678KM
14T1234-5678KM
1T1234-5678KM
123360T1234-5678KM
123345V1234-5678KM
123345T12345-5678KM
123345T1234-56789KM
123345T-5678KM
123345T123-KM
123345T123-56KMK
123345T1234-56KMK
123345T12-5678KKM
123345T1-5
123345T1234567KM
123345T1235678KKM
123345!56T123-567KKM
123!345T123-567KKM
123345T12!3-56KKM
123345T12-5!6KKM
123345T12-5K!KM
1233457T1234-5678K
123345T1234-5678GH
123345T1234-5678MK
123345T1234-5678UUUU
null
000359T1234K-5678KM
123345TK-5678KM
123345T1234--5678KM
"""#
let stringRange = NSRange(location: 0, length: testString.utf16.count)
if let firstMatch = regex.firstMatch(in: testString, range: stringRange) {
let result: [String] = (1 ..< firstMatch.numberOfRanges).map { (testString as NSString).substring(with: firstMatch.range(at: $0)) }
print(result)
} else {
print("No matches were found.")
}
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