Twoje pytanie zawiera 2 ważne części:
Wyrażenie regularne, które pasuje do wszystkich znaków, z wyjątkiem pierwszych 6 i ostatnie 2
let regexPattern = "(?<=.{6}).(?=.*.{2}$)"
i
Rozszerzenia na String
to bierze wyrażenie regularne i maskuje go:
extension String {
func masked(matching regexPattern: String, with template: String = "*") throws -> String {
let regex = try NSRegularExpression(pattern: regexPattern, options: NSRegularExpression.Options.caseInsensitive)
let range = NSMakeRange(0, count)
return regex.stringByReplacingMatches(in: self, options: [], range: range, withTemplate: template)
}
}
Zastosowanie:
let cardNumber = "5890040000000016"
let regexPattern = "(?<=.{6}).(?=.*.{2}$)"
print("Output:", try! cardNumber.masked(matching: regexPattern))
Wyjście: 589004********16
#"..."#
raczej niż"..."
z powodu drażniącego postać uciekającego do wyrażenia regularnego