How to validate MasterCard number using Regular Expression | Python3 program to validate Master Card number using regular expression ; Function to validate Master Card number using regular expression . ; Regex to check valid Master Card number . ; Compile the ReGex ; If the string is empty return false ; Return if the string matched the ReGex ; Test Case 1 : ; Test Case 2 : ; Test Case 3 : ; Test Case 4 : ; Test Case 5 : str5 = "2221149a635843"
import re NEW_LINE def isValidMasterCardNo ( str ) : NEW_LINE INDENT regex = " ^ 5[1-5 ] [ 0-9 ] { 14 } | " + NEW_LINE INDENT " ^ ( 222[1-9 ] ▁ 22[3-9 ] \\d ▁ " + "2[3-6 ] \\d { 2 } ▁ 27[0-1 ] \\d ▁ " + "2720 ) [ 0-9 ] { 12 } $ " NEW_LINE DEDENT p = re . compile ( regex ) NEW_LINE if ( str == None ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( re . search ( p , str ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT str1 = "5114496353984312" NEW_LINE print ( isValidMasterCardNo ( str1 ) ) NEW_LINE str2 = "2720822463109651" NEW_LINE print ( isValidMasterCardNo ( str2 ) ) NEW_LINE str3 = "5582822410" NEW_LINE print ( isValidMasterCardNo ( str3 ) ) NEW_LINE str4 = "6082822463100051" NEW_LINE print ( isValidMasterCardNo ( str4 ) ) NEW_LINE print ( isValidMasterCardNo ( str5 ) ) NEW_LINE