Home > Net >  Card Number Masking
Card Number Masking

Time:11-18

I'm trying to mask card number with regex. First 6 and last 2 chars can be shown other should "*".

let cardNumber: String = "5890040000000016"

print("Output: ", cardNumber.mask(regexPattern:"XXXXXXX")) // Output: 589004********16

How can I do that in swift?

CodePudding user response:

You can concatenate substrings together:

let cardNumber = "5890040000000016"

let start = cardNumber.startIndex ..< cardNumber.index(cardNumber.startIndex, offsetBy: 6)
let end = cardNumber.index(cardNumber.endIndex, offsetBy: -2) ..< cardNumber.endIndex
let result = cardNumber[start]   Array(repeating: "*", count: cardNumber.count - 8)   cardNumber[end]
print(result)

// Prints: 589004********16

CodePudding user response:

Perhaps you're looking for something like this:

let s = "5890040000000016"
let patt = ##"^(\d{6})(.*)(\d{2})$"## // this is your pattern
let reg = try! NSRegularExpression(pattern: patt, options: [])
if let m = reg.firstMatch(in: s, options: [], range: NSRange(s.startIndex..<s.endIndex, in: s)) {
    let r = m.range(at:2)
    let result = s.replacingCharacters(in: Range(r, in:s)!, with: String(repeating: "X", count: r.length))
    print(result) // 589004XXXXXXXX16
}

CodePudding user response:

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

  • Related