iosswiftcredit-cardbanking

How to set the pattern for Credit Card PAN NUMBER with regularExpresion in Swift?


I am trying to read pan numbers from physical credit cards using Vision Framework. For this I use a string extension for filtering the reuslts.

Here is an example for US phone numbers:

func extractPhoneNumber() -> (Range<String.Index>, String)? {
        let pattern = #"""
        (?x)                    # Verbose regex, allows comments
        (?:\+1-?)?              # Potential international prefix, may have -
        [(]?                    # Potential opening (
        \b(\w{3})               # Capture xxx
        [)]?                    # Potential closing )
        [\ -./]?                # Potential separator
        (\w{3})                 # Capture xxx
        [\ -./]?                # Potential separator
        (\w{4})\b               # Capture xxxx
        """#

        guard let range = self.range(of: pattern, options: .regularExpression, range: nil, locale: nil) else {
            // No phone number found.
            return nil
        }

I need a different pattern for Card Pan numbers in the following form eg. 0000 0000 0000 0000

Thank you for the help!


Solution

  • The pattern that worked for me is:

    let pattern = #"""
            \d{4} \d{4} \d{4} \d{4}
            """#
    

    Thank you Scriptable!