How to validate MasterCard number using Regular Expression | Java 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 ; Find match between given string and regular expression using Pattern . matcher ( ) ; Return if the string matched the ReGex ; Driver code ; Test Case 1 : ; Test Case 2 : ; Test Case 3 : ; Test Case 4 : ; Test Case 5 :
import java . util . regex . * ; class GFG { public static boolean isValidMasterCardNo ( String str ) { String regex = " ^ 5[1-5 ] [ 0-9 ] { 14 } | " + " ^ ( 222[1-9 ] ▁ 22[3-9 ] \\ d ▁ " + "2[3-6 ] \\ d { 2 } ▁ 27[0-1 ] \\ d ▁ " + "2720 ) [ 0-9 ] { 12 } $ " ; Pattern p = Pattern . compile ( regex ) ; if ( str == null ) { return false ; } Matcher m = p . matcher ( str ) ; return m . matches ( ) ; } public static void main ( String args [ ] ) { String str1 = "5114496353984312" ; System . out . println ( isValidMasterCardNo ( str1 ) ) ; String str2 = "2720822463109651" ; System . out . println ( isValidMasterCardNo ( str2 ) ) ; String str3 = "5582822410" ; System . out . println ( isValidMasterCardNo ( str3 ) ) ; String str4 = "6082822463100051" ; System . out . println ( isValidMasterCardNo ( str4 ) ) ; String str5 = "2221149a635 # # 843" ; System . out . println ( isValidMasterCardNo ( str5 ) ) ; } }