import Foundation
let pattern = #"\b([A-Z]+)0(?=\d{3}\b)"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"""
SK0498 should return SK498 (total digits = 4 = omit the single leading zero)
AA007 should still return AA007 (because the leading zeros are double, and total digits is only 3)
UA2138 returns UA2138 (no leading zeros involved)
BA023 should return BA023 (keep the zero because total number of digits is only 3), however BA0234 should return BA234 (total digits is 4 with a single leading zero that should be omitted).
AA0007
"""#
let stringRange = NSRange(location: 0, length: testString.utf16.count)
let substitutionString = #"$1"#
let result = regex.stringByReplacingMatches(in: testString, range: stringRange, withTemplate: substitutionString)
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