Home > Back-end >  Python Regex Check for Credit Cards
Python Regex Check for Credit Cards

Time:10-15

I created a script to look for specific card numbers, of which, are included in the list credit_cards. Simple function, it just marks each one as Valid/Invalid depending on the regex pattern listed.

My problem stems from understanding how to implement this regex check, with the inclusion of spaces, and periods. So if a card were to have 3423.3423.2343.3433 or perhaps 3323 3223 442 3234. I do include hyphens as a delimiter I'm checking for, but how can I also include multiple delimeters, like periods and spaces?

Here is my script-

import re

credit_cards = ['6011346728478930','5465625879615786','5711424424442444',
    '5000-2368-7954-3214', '4444444444444444', '5331625879615786', '5770625879615786',
    '5750625879615786', '575455879615786']

def World_BINS(credit_cards):
    valid_BINS = r"^5(?:465|331|000|[0-9]{2})(-?\d{4}){3}$"

    do_not_repeat = r"((\d)-?(?!(-?\2){3})){16}"

    filters = valid_BINS, do_not_repeat

    for num in credit_cards:
        if all(re.match(f, num) for f in filters):
            print(f"{num} is Valid")
        else:
            print (f"{num} is invalid")


World_BINS(credit_cards)

CodePudding user response:

You can use

import re
credit_cards = ['5000 2368 7954 3214','5000.2368.7954.3214','6011346728478930','5465625879615786', '5711424424442444', '5000-2368-7954-3214', '4444444444444444', '5331625879615786', '5770625879615786','5750625879615786', '575455879615786']

def World_BINS(credit_cards):
    valid_BINS = r"^5(?:465|331|000|[0-9]{2})(?=([\s.-]?))(\1\d{4}){3}$"
    do_not_repeat = r"^((\d)([\s.-]?)(?!(\3?\2){3})){16}$"

    filters = [valid_BINS, do_not_repeat]

    for num in credit_cards:
        if all(re.match(f, num) for f in filters):
            print(f"{num} is Valid")
        else:
            print (f"{num} is invalid")


World_BINS(credit_cards)

See the Python demo.

The (?=([\s.-]?))(\1\d{4}){3} in the first regex captures a whitespace (\s), . or - as an optional char into Group 1 and then \1 refers to the value (either an empty string, or whitespace, or . or -) in the next group. The lookaround is used to make sure the delimiters / separators are used consistently in the string.

In the second regex, ^((\d)([\s.-]?)(?!(\3?\2){3})){16}$, similar technique is used, the whitespace, . or - is captured into Group 3, and the char is optionally matched inside the subsequent quantified group to refer to the same value.

  • Related