La tua domanda contiene 2 parti importanti:
Un'espressione regolare che corrisponde a tutti i caratteri, ma prime 6 e le ultime 2
let regexPattern = "(?<=.{6}).(?=.*.{2}$)"
e
L'estensione del String
che prende la regex e maschere:
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)
}
}
Utilizzo:
let cardNumber = "5890040000000016"
let regexPattern = "(?<=.{6}).(?=.*.{2}$)"
print("Output:", try! cardNumber.masked(matching: regexPattern))
Uscita: 589004********16
#"..."#
piuttosto che"..."
a causa dei fastidiosi carattere di escape per regex