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 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 contain any alphabet or 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:
regex = "^4[0-9]{12}(?:[0-9]{3})?$";
Where:
- ^ represents the starting of the string.
- 4 represents the string that should start with 4.
- [0-9]{12} represents the next twelve digits should be any between 0-9.
- ( represents the start 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:
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)