MasterCard number validation using Regular Expression in Python

In this article, we will learn how to check whether the given string is a valid MasterCard number or not using Regular Expression in Python.

A valid MasterCard number must satisfy the following conditions

  • It should contain 16 digits
  • It should begin with either two digits number may go from 51 to 55 or four digits number may go from 2221 to 2720.
  • On account of 51 to 55, the following fourteen digits ought to be any number between 0-9.
  • On account of 2221 to 2720, the following twelve digits ought to be any number between 0-9.
  • It should not contain any letters in order and exceptional characters.

Examples

Input: 5303954139236062
Output: True

Input: 3535233563879043
Output: False

MasterCard validation in Python

Regular expression: “^5[1-5][0-9]{14}|^(222[1-9]|22[3-9]\\d|2[3-6]\\d{2}|27[0-1]\\d|2720)[0-9]{12}$”

Where

  • ^ indicates the starting of the string.
  • 5[1-5] represents the first two-digits, range from 51 to 55.
  • [0-9]{14} indicates the next 14 digits.
  • | indicates or
  • ( indicates the starting of the group.
  • 222[1-9] indicates the first 4 digits, ranging from 2221 to 2229.
  • | indicates or
  • 22[3-9] \\ d indicates the first 4 digits, ranging from 2230 to 2299.
  • | indicates or
  • 2[3-6]\\d{2} indicates the first 4 digits, ranging from 2300 to 2699.
  • | indicates or
  • 27[0-1]\\d indicates the first 4 digits, ranging from 2700 to 2719.
  • | indicates or
  • 2720 indicates the first 4 digits start with 2720.
  • ) indicates the ending of the group.
  • [0-9]{12} indicates the next 12 digits, ranging from 0 to 9.
  • $ indicates the ending of the string.
import re

def isValidMasterCard(string):
    regex = "^5[1-5][0-9]{14}|" + "^(222[1-9]|22[3-9]\\d|" + "2[3-6]\\d{2}|27[0-1]\\d|" + "2720)[0-9]{12}$"
    p = re.compile(regex)
    if (string == None):
        return False
    if(re.search(p, string)):
        return True
    else:
        return False
string = input("Enter the MasterCard number: ")
if(isValidMasterCard(string)):
    print("Valid Number")
else:
    print("Not Valid Number")

Output

Enter the MasterCard number: 5438052940092945
Valid Number

Enter the MasterCard number: 4438052940092945 
Not Valid Number

Firstly, compile the regex. Check if the given string matched with the regex then return true else return false.

Also, read

Leave a Reply

Your email address will not be published. Required fields are marked *