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.swift580 chars15 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