find social security numbers in a string using regex in swift

To find social security numbers in a string using regex in Swift, you can use the NSRegularExpression class provided by Foundation framework. Here's an example code snippet:

main.swift
let input = "John Doe's SSN is 123-45-6789 and Jane Doe's SSN is 987-65-4321."
let pattern = "\\d{3}-\\d{2}-\\d{4}" // Regex pattern for social security numbers

do {
    let regex = try NSRegularExpression(pattern: pattern, options: .caseInsensitive)
    let matches = regex.matches(in: input, options: [], range: NSRange(location: 0, length: input.utf16.count))
    
    for match in matches {
        let ssn = (input as NSString).substring(with: match.range)
        print("Found SSN: \(ssn)")
    }
} catch {
    print("Regex pattern error: \(error.localizedDescription)")
}
580 chars
15 lines

In this example, we first define an input string that contains two social security numbers. We also define a regex pattern for social security numbers as \\d{3}-\\d{2}-\\d{4}. This pattern matches any string that contains three digits followed by a dash, then two digits followed by another dash, and finally four digits.

We then create an instance of NSRegularExpression with the regex pattern and search options. We pass the input string along with a range that covers the entire string. We use the matches(in:options:range:) method to find all matches in the input string.

Finally, we iterate over the array of matches and extract each social security number using the range property of each match. We print out each found social security number to the console.

It's important to be aware of data privacy and security when handling sensitive information like social security numbers. Be sure to handle the extracted SSNs appropriately and securely.

gistlibby LogSnag