Your question contains 2 important parts:
A regex that matches all characters but first 6 and last 2
let regexPattern = "(?<=.{6}).(?=.*.{2}$)"
and
An extension on the String
that takes the regex and masks it:
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)
}
}
Usage:
let cardNumber = "5890040000000016"
let regexPattern = "(?<=.{6}).(?=.*.{2}$)"
print("Output:", try! cardNumber.masked(matching: regexPattern))
Output: 589004********16