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:
383 chars13 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