find credit card numbers in a string using regex in python

To find credit card numbers in a string in Python, you can use regular expressions (regex) with the re module. Here is an example code block that uses regex to find credit card numbers in a string:

import re

string = "Alice's credit card number is 1234-5678-9101-1121. Bob's credit card number is 2345-6789-1011-1213."

# define a regex pattern for matching credit card numbers
pattern = r"\b\d{4}[- ]?\d{4}[- ]?\d{4}[- ]?\d{4}\b"

# search for credit card numbers in the string using the findall function
matches = re.findall(pattern, string)

# print the matches
print(matches)
383 chars
13 lines

In this code, the regex pattern \b\d{4}[- ]?\d{4}[- ]?\d{4}[- ]?\d{4}\b matches credit card numbers that start with four digits, followed by optional hyphens or spaces, and end with four digits. The \b before and after the pattern ensure that the pattern is matched as a whole word and not as part of a longer number.

The re.findall() function searches the string for all matches of the pattern and returns them as a list. In this case, the function returns a list with the two credit card numbers found in the string.

Note that this regex pattern may not match all valid credit card numbers, and may also match some non-credit-card numbers that happen to have a similar format. Therefore, it's important to carefully test and validate your regex pattern on a variety of input strings before using it in production code.

gistlibby LogSnag