find social security numbers in a string using regex in python

To find social security numbers in a string using regex in Python, you can use the re module in Python to search for a pattern of 9 digits separated by either dashes or spaces. Here's an example code snippet:

main.py
import re

text = "My SSN is 123-45-6789 and yours is 987 65 4321. Let's be careful with our social security numbers!"

ssn_pattern = re.compile(r'\d{3}[-\s]?\d{2}[-\s]?\d{4}')

ssns_found = re.findall(ssn_pattern, text)

print(ssns_found)
240 chars
10 lines

In this code, we first import the re module. We then define our sample text that we want to search for social security numbers.

Next, we define our regular expression pattern using the re.compile() function. The pattern \d{3} matches any three digits, and [-\s] matches either a dash or a space character. The question mark ? after the [-\s] character class means that it is optional, so we can match social security numbers with or without dashes/spaces between the numbers.

Finally, we use the re.findall() function to search for all instances of our pattern in the text and return them as a list of strings.

When running this code, the output will be:

['123-45-6789', '987 65 4321']

indicating that we successfully found both social security numbers in the input string.

gistlibby LogSnag