How to validate Visa Card number using Regular Expression

15 Feb, 2021
Given a string str, the task is to check whether the given string is 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 be starts with 4.If the cards have 13 digits the next twelve digits should be any number between 0-9.If the cards have 16 digits the next fifteen digits should be any number between 0-9.It should not contains any alphabets and special characters.
It should be 13 or 16 digits long, new cards have 16 digits and old cards have 13 digits.
It should be starts with 4.
If the cards have 13 digits the next twelve digits should be any number between 0-9.
If the cards have 16 digits the next fifteen digits should be any number between 0-9.
It should not contains any alphabets and special characters.
Examples:  
Input: str = “4155279860457”; Output: true Explanation: The given string satisfies all the above mentioned conditions. Therefore it is a valid Visa Card number. Input: str = “4155279”; Output: false. Explanation: The given string has 7 digits. Therefore it is not a valid Visa Card number. Input: str = “6155279860457”; Output: false. Explanation: The given string doesn’t starts with 4. Therefore it is not a valid Visa 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 valid Visa Card number as mentioned below:  
Get the String.
Create a regular expression to check valid Visa Card number as mentioned below:  
regex = "^4[0-9]{12}(?:[0-9]{3})?$";
Where: ^ represents the starting of the string.4 represents the string should be starts with 4.[0-9]{12} represents the next twelve digits should be any between 0-9.( represents the starting of the group.? represents the 0 or 1 time.[0-9]{3} represents the next three digits should be any between 0-9.) represents the ending of the group.? represents the 0 or 1 time.$ 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.
Where: ^ represents the starting of the string.4 represents the string should be starts with 4.[0-9]{12} represents the next twelve digits should be any between 0-9.( represents the starting of the group.? represents the 0 or 1 time.[0-9]{3} represents the next three digits should be any between 0-9.) represents the ending of the group.? represents the 0 or 1 time.$ represents the ending of the string.
^ represents the starting of the string.
4 represents the string should be starts with 4.
[0-9]{12} represents the next twelve digits should be any between 0-9.
( represents the starting of the group.
? represents the 0 or 1 time.
[0-9]{3} represents the next three digits should be any between 0-9.
) represents the ending of the group.
? represents the 0 or 1 time.
$ 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++
Java
Python3
// C++ program to validate// Visa Card number// using Regular Expression#include <iostream>#include <regex>using namespace std; // Function to validate Visa Card numberbool isValidVisaCardNo(string str){   // Regex to check valid Visa Card number  const regex pattern("^4[0-9]{12}(?:[0-9]{3})?$");   // If the Visa Card number  // is empty return false  if (str.empty())  {     return false;  }   // Return true if the Visa Card number  // matched the ReGex  if(regex_match(str, pattern))  {    return true;  }  else  {    return false;  }} // Driver Codeint main(){     // Test Case 1:  string str1 = "4155279860457";  cout << isValidVisaCardNo(str1) << endl;   // Test Case 2:  string str2 = "4155279860457201";  cout << isValidVisaCardNo(str2) << endl;   // Test Case 3:  string str3 = "4155279";  cout << isValidVisaCardNo(str3) << endl;   // Test Case 4:  string str4 = "6155279860457";  cout << isValidVisaCardNo(str4) << endl;   // Test Case 5:  string str5 = "415a27##60457";  cout << isValidVisaCardNo(str5) << endl;   return 0;} // This code is contributed by yuvraj_chandra
// Java program to validate// Visa Card number// using regular expressionimport java.util.regex.*;class GFG {     // Function to validate    // Visa Card number.    // using regular expression.    public static boolean    isValidVisaCardNo(String str)    {        // Regex to check valid.        // Visa Card number        String regex = "^4[0-9]{12}(?:[0-9]{3})?$";         // 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 = "4155279860457";        System.out.println(            isValidVisaCardNo(str1));         // Test Case 2:        String str2 = "4155279860457201";        System.out.println(            isValidVisaCardNo(str2));         // Test Case 3:        String str3 = "4155279";        System.out.println(            isValidVisaCardNo(str3));         // Test Case 4:        String str4 = "6155279860457";        System.out.println(            isValidVisaCardNo(str4));         // Test Case 5:        String str5 = "415a27##60457";        System.out.println(            isValidVisaCardNo(str5));    }}
# Python3 program to validate Visa# Card number using regular expressionimport re # Function to validate Visa Card# number using regular expression.def isValidVisaCardNo(string):         # Regex to check valid Visa    # Card number    regex = "^4[0-9]{12}(?:[0-9]{3})?$";     # Compile the ReGex    p = re.compile(regex);         # If the string is empty    # return false    if (string == ''):        return False;             # Pattern class contains matcher()    # method to find matching between    # given string and regular expression.    m = re.match(p, string);         # Return True if the string    # matched the ReGex else False    if m is None:        return False    else:        return True # Driver codeif __name__ == "__main__":         # Test Case 1    str1 = "4155279860457";    print(isValidVisaCardNo(str1));         # Test Case 2    str2 = "4155279860457201";    print(isValidVisaCardNo(str2));         # Test Case 3    str3 = "4155279";    print(isValidVisaCardNo(str3));         # Test Case 4    str4 = "6155279860457";    print(isValidVisaCardNo(str4));         # Test Case 5    str5 = "415a27##60457";    print(isValidVisaCardNo(str5));     # This code is contributed by AnkitRai01
true
true
false
false
false
 
ankthon
yuvraj_chandra
CPP-regex
java-regular-expression
regular-expression
Pattern Searching
Strings
Strings
Pattern Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.