find credit card numbers in a string using regex in swift

To find credit card numbers in a string using regex in Swift, you can use the built-in NSRegularExpression class. Here's an example implementation:

main.swift
func findCreditCardNumbers(in string: String) -> [String] {
    var creditCardNumbers: [String] = []
    
    do {
        let regex = try NSRegularExpression(pattern: "\\b(?:\\d[ -]*?){13,16}\\b", options: [])
        
        let matches = regex.matches(in: string, options: [], range: NSRange(location: 0, length: string.utf16.count))
        
        for match in matches {
            if let range = Range(match.range, in: string) {
                creditCardNumbers.append(String(string[range]))
            }
        }
    } catch {
        print("Regex error: \(error.localizedDescription)")
    }
    
    return creditCardNumbers
}
642 chars
20 lines

The regex pattern used in this example will match any sequence of 13-16 digits separated by spaces or dashes. The resulting credit card numbers are returned in an array of strings. You can modify the regex pattern to match different credit card number formats if needed.

gistlibby LogSnag