Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Pattern Searching
  • Tutorial on Pattern Searching
  • Naive Pattern Searching
  • Rabin Karp
  • KMP Algorithm
  • Z Algorithm
  • Trie for Pattern Seaching
  • Manacher Algorithm
  • Suffix Tree
  • Ukkonen's Suffix Tree Construction
  • Boyer Moore
  • Aho-Corasick Algorithm
  • Wildcard Pattern Matching
Open In App
Next Article:
How to Validate MICR Code using Regular Expression?
Next article icon

How to validate MasterCard number using Regular Expression

Last Updated : 20 Dec, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given string str, the task is to check whether the given string is a valid Master Card number or not by using Regular Expression. 
The valid Master Card number must satisfy the following conditions. 

  1. It should be 16 digits long.
  2. It should start with either two digits numbers may range from 51 to 55 or four digits numbers may range from 2221 to 2720.
  3. In the case of 51 to 55, the next fourteen digits should be any number between 0-9.
  4. In the case of 2221 to 2720, the next twelve digits should be any number between 0-9.
  5. It should not contain any alphabet or special characters.

Examples: 

Input: str = “5114496353984312”; 
Output: true 
Explanation: 
The given string satisfies all the above mentioned conditions. Therefore, it is a valid Master Card number.
Input: str = “5582822410”; 
Output: false 
Explanation: 
The given string has 10 digits. Therefore, it is not a valid Master Card number.
Input: str = “6082822463100051”; 
Output: false 
Explanation: 
The given string does not start with either two digits number may range from 51 to 55 or four digits number may range from 2221 to 2720. Therefore, it is not a valid Master Card number. 

Approach: The idea is to use Regular Expression to solve this problem. The following steps can be followed to compute the answer. 

  • Get the String.
  • Create a regular expression to check the valid Master Card number as mentioned below: 
     

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}$”; 

  • Where: 
    • ^ represents the starting of the string.
    • 5[1-5] represents the first two-digit number may range from 51 to 55.
    • [0-9]{14} represents the next fourteen digits should be any between 0-9.
    • | represents the or.
    • ( represents the start of the group.
    • 222[1-9] represents the first four-digit number may range from 2221 to 2229.
    • | represents the or.
    • 22[3-9]\\d represents the first four-digit number that may range from 2230 to 2299.
    • | represents the or.
    • 2[3-6]\\d{2} represents the first four-digit number may range from 2300 to 2699.
    • | represents the or.
    • 27[0-1]\\d represents the first four-digit number may range from 2700 to 2719.
    • | represents the or.
    • 2720 represents the first four-digit may start with 2720.
    • ) represents the ending of the group.
    • [0-9]{12} represents the next twelve digits should be any between 0-9.
    • $ represents the ending of the string.
  • Match the given string with the Regular Expression. 
    In Java, this can be done by using Pattern.matcher()
    In C++, this can be done by using regex_match()
  • Return true if the string matches with the given regular expression, else return false.

Below is the implementation of the above approach:
 

C++




// C++ program to validate
// Master Card number
// using Regular Expression
#include <iostream>
#include <regex>
using namespace std;
 
// Function to validate Master Card number
bool isValidMasterCardNo(string str)
{
 
  // Regex to check valid Master Card number
  const regex pattern("^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}$");
 
  // If the Master Card number
  // is empty return false
  if (str.empty())
  {
     return false;
  }
 
  // Return true if the Master Card number
  // matched the ReGex
  if(regex_match(str, pattern))
  {
    return true;
  }
  else
  {
    return false;
  }
}
 
// Driver Code
int main()
{
  // Test Case 1:
  string str1 = "5114496353984312";
  cout << isValidMasterCardNo(str1) << endl;
 
  // Test Case 2:
  string str2 = "2720822463109651";
  cout << isValidMasterCardNo(str2) << endl;
 
  // Test Case 3:
  string str3 = "5582822410";
  cout << isValidMasterCardNo(str3) << endl;
 
  // Test Case 4:
  string str4 = "6082822463100051";
  cout << isValidMasterCardNo(str4) << endl;
 
  // Test Case 5:
  string str5 = "2221149a635##843";
  cout << isValidMasterCardNo(str5) << endl;
 
  return 0;
}
 
// This code is contributed by yuvraj_chandra
 
 

Java




// Java program to validate
// Master Card number
// using regular expression
 
import java.util.regex.*;
class GFG {
 
    // Function to validate
    // Master Card number
    // using regular expression.
    public static boolean
    isValidMasterCardNo(String str)
    {
 
        // Regex to check valid
        // Master Card number.
        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}$";
 
        // Compile the ReGex
        Pattern p
            = Pattern.compile(regex);
 
        // If the string is empty
        // return false
        if (str == null) {
            return false;
        }
 
        // Find match between given string
        // and regular expression
        // using Pattern.matcher()
        Matcher m = p.matcher(str);
 
        // Return if the string
        // matched the ReGex
        return m.matches();
    }
 
    // Driver code
    public static void main(String args[])
    {
        // Test Case 1:
        String str1 = "5114496353984312";
        System.out.println(
            isValidMasterCardNo(str1));
 
        // Test Case 2:
        String str2 = "2720822463109651";
        System.out.println(
            isValidMasterCardNo(str2));
 
        // Test Case 3:
        String str3 = "5582822410";
        System.out.println(
            isValidMasterCardNo(str3));
 
        // Test Case 4:
        String str4 = "6082822463100051";
        System.out.println(
            isValidMasterCardNo(str4));
 
        // Test Case 5:
        String str5 = "2221149a635##843";
        System.out.println(
            isValidMasterCardNo(str5));
    }
}
 
 

Python3




# Python3 program to validate
# Master Card number
# using regular expression
import re
 
# Function to validate
# Master Card number
# using regular expression.
def isValidMasterCardNo(str):
 
    # Regex to check valid
    # Master Card number.
    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}$"
     
    # Compile the ReGex
    p = re.compile(regex)
 
    # If the string is empty
    # return false
    if (str == None):
        return False
 
    # Return if the string
    # matched the ReGex
    if(re.search(p, str)):
        return True
    else:
        return False
 
# Driver code
 
# Test Case 1:
str1 = "5114496353984312"
print(isValidMasterCardNo(str1))
 
# Test Case 2:
str2 = "2720822463109651"
print(isValidMasterCardNo(str2))
 
# Test Case 3:
str3 = "5582822410"
print(isValidMasterCardNo(str3))
 
# Test Case 4:
str4 = "6082822463100051"
print(isValidMasterCardNo(str4))
 
# Test Case 5:
str5 = "2221149a635##843"
print(isValidMasterCardNo(str5))
 
# This code is contributed by avanitrachhadiya2155
 
 

C#




// C# program to validate
// Master Card number
// using regular expression
 
using System;
using System.Text.RegularExpressions;
 
class GFG {
 
  // Function to validate
  // Master Card number
  // using regular expression.
  public static bool
    isValidMasterCardNo(string str)
  {
 
    // Regex to check valid
    // Master Card number.
    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}$";
 
    // Compile the ReGex
    Regex p = new Regex(regex);
 
    // If the string is empty
    // return false
    if (str == null) {
      return false;
    }
 
    // Find match between given string
    // and regular expression
    // using Pattern.matcher()
    Match m = p.Match(str);
 
    // Return if the string
    // matched the ReGex
    return m.Success;
  }
 
  // Driver code
  public static void Main()
  {
    // Test Case 1:
    string str1 = "5114496353984312";
    Console.WriteLine(
      isValidMasterCardNo(str1));
 
    // Test Case 2:
    string str2 = "2720822463109651";
    Console.WriteLine(
      isValidMasterCardNo(str2));
 
    // Test Case 3:
    string str3 = "5582822410";
    Console.WriteLine(
      isValidMasterCardNo(str3));
 
    // Test Case 4:
    string str4 = "6082822463100051";
    Console.WriteLine(
      isValidMasterCardNo(str4));
 
    // Test Case 5:
    string str5 = "2221149a635##843";
    Console.WriteLine(
      isValidMasterCardNo(str5));
  }
}
 
// This code is contributed by Aman Kumar.
 
 

Javascript




// Javascript program to validate
// MasterCard number  using Regular Expression
 
// Function to validate the
// MasterCard_Number 
function isValid_MasterCard_Number(MasterCard_Number) {
    // Regex to check valid
    // MasterCard_Number 
    let regex = new RegExp(/^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}$/);
 
    // if MasterCard_Number
    // is empty return false
    if (MasterCard_Number == null) {
        return "false";
    }
 
    // Return true if the MasterCard_Number
    // matched the ReGex
    if (regex.test(MasterCard_Number) == true) {
        return "true";
    }
    else {
        return "false";
    }
}
 
// Driver Code
// Test Case 1:
let str1 = "5114496353984312";
console.log(isValid_MasterCard_Number(str1));
 
// Test Case 2:
let str2 = "2720822463109651";
console.log(isValid_MasterCard_Number(str2));
 
// Test Case 3:
let str3 = "5582822410";
console.log(isValid_MasterCard_Number(str3));
 
// Test Case 4:
let str4 = "6082822463100051";
console.log(isValid_MasterCard_Number(str4));
 
// Test Case 5:
let str5 = "2221149a635##843";
console.log(isValid_MasterCard_Number(str5));
 
// Test Case 6:
let str6 = "RAH12071998";
console.log(isValid_MasterCard_Number(str6));
 
// This code is contributed by Rahul Chauhan
 
 
Output: 
true true false false false

 

Time Complexity: O(N) for each test case, where N is the length of the given string. 
Auxiliary Space: O(1)  



Next Article
How to Validate MICR Code using Regular Expression?
author
prashant_srivastava
Improve
Article Tags :
  • DSA
  • Pattern Searching
  • Strings
  • CPP-regex
  • java-regular-expression
  • regular-expression
Practice Tags :
  • Pattern Searching
  • Strings

Similar Reads

  • How to validate CVV number using Regular Expression
    Given string str, the task is to check whether it is a valid CVV (Card Verification Value) number or not by using Regular Expression. The valid CVV (Card Verification Value) number must satisfy the following conditions: It should have 3 or 4 digits.It should have a digit between 0-9.It should not ha
    5 min read
  • How to validate ISIN using Regular Expressions
    ISIN stands for International Securities Identification Number. Given string str, the task is to check whether the given string is a valid ISIN(International Securities Identification Number) or not by using Regular Expression. The valid ISIN(International Securities Identification Number) must sati
    6 min read
  • How to validate Visa Card number using Regular Expression
    Given a string str, the task is to check whether the given string is a valid Visa Card number or not by using Regular Expression. The valid Visa Card number must satisfy the following conditions: It should be 13 or 16 digits long, new cards have 16 digits and old cards have 13 digits.It should start
    6 min read
  • How to validate PAN Card number using Regular Expression
    Given string str of alphanumeric characters, the task is to check whether the string is a valid PAN (Permanent Account Number) Card number or not by using Regular Expression.The valid PAN Card number must satisfy the following conditions: It should be ten characters long.The first five characters sh
    6 min read
  • How to Validate MICR Code using Regular Expression?
    MICR stands for Magnetic Ink Character Recognition. This technology provides transaction security, ensuring the correctness of bank cheques. MICR code makes cheque processing faster and safer. MICR Technology reduces cheque-related fraudulent activities. Structure of a Magnetic Ink Character Recogni
    6 min read
  • How to validate Indian Passport number using Regular Expression
    Given a string str of alphanumeric characters, the task is to check whether the given string is a valid passport number or not by using Regular Expression. A valid passport number in India must satisfy the following conditions: It should be eight characters long.The first character should be an uppe
    5 min read
  • How to validate Indian driving license number using Regular Expression
    Given string str, the task is to check whether the given string is a valid Indian driving license number or not by using Regular Expression.The valid Indian driving license number must satisfy the following conditions: It should be 16 characters long (including space or hyphen (-)).The driving licen
    7 min read
  • How to validate IFSC Code using Regular Expression
    Given string str, the task is to check whether the given string is a valid IFSC (Indian Financial System) Code or not by using Regular Expression. The valid IFSC (Indian Financial System) Code must satisfy the following conditions: It should be 11 characters long.The first four characters should be
    8 min read
  • How to validate MAC address using Regular Expression
    Given string str, the task is to check whether the given string is a valid MAC address or not by using Regular Expression. A valid MAC address must satisfy the following conditions: It must contain 12 hexadecimal digits.One way to represent them is to form six pairs of the characters separated with
    6 min read
  • How to validate a domain name using Regular Expression
    Given string str, the task is to check whether the given string is a valid domain name or not by using Regular Expression.The valid domain name must satisfy the following conditions: The domain name should be a-z or A-Z or 0-9 and hyphen (-).The domain name should be between 1 and 63 characters long
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences