How to validate Visa Card number using Regular Expression

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:

  1. It should be 13 or 16 digits long, new cards have 16 digits and old cards have 13 digits.
  2. It should be starts with 4.
  3. If the cards have 13 digits the next twelve digits should be any number between 0-9.
  4. If the cards have 16 digits the next fifteen digits should be any number between 0-9.
  5. 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.

  1. Get the String.
  2. 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.
  3. Match the given string with the Regular Expression. In Java, this can be done by using Pattern.matcher().
  4. Return true if the string matches with the given regular expression, else return false.

Below is the implementation of the above approach:

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to validate
// Visa Card number
// using regular expression
import 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));
    }
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to validate Visa 
# Card number using regular expression 
import 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 code 
if __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

chevron_right


Output:

true
true
false
false
false

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : AnkitRai01