How to validate Visa Card number using Regular Expression | Python3 program to validate Visa Card number using regular expression ; Function to validate Visa Card number using regular expression . ; Regex to check valid Visa Card number ; Compile the ReGex ; If the string is empty return false ; Pattern class contains matcher ( ) method to find matching between given string and regular expression . ; Return True if the string matched the ReGex else False ; Driver code ; Test Case 1 ; Test Case 2 ; Test Case 3 ; Test Case 4 ; Test Case 5 str5 = "415a2760457" ;
import re NEW_LINE def isValidVisaCardNo ( string ) : NEW_LINE INDENT regex = " ^ 4[0-9 ] { 12 } ( ? : [0-9 ] { 3 } ) ? $ " ; NEW_LINE p = re . compile ( regex ) ; NEW_LINE if ( string == ' ' ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT m = re . match ( p , string ) ; NEW_LINE if m is None : NEW_LINE INDENT return False NEW_LINE DEDENT else : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str1 = "4155279860457" ; NEW_LINE print ( isValidVisaCardNo ( str1 ) ) ; NEW_LINE str2 = "4155279860457201" ; NEW_LINE print ( isValidVisaCardNo ( str2 ) ) ; NEW_LINE str3 = "4155279" ; NEW_LINE print ( isValidVisaCardNo ( str3 ) ) ; NEW_LINE str4 = "6155279860457" ; NEW_LINE print ( isValidVisaCardNo ( str4 ) ) ; NEW_LINE print ( isValidVisaCardNo ( str5 ) ) ; NEW_LINE DEDENT