How to validate SSN ( Social Security Number ) using Regular Expression | Java program to check valid SSN ( Social Security Number ) using regex . ; Function to validate SSN ( Social Security Number ) . ; Regex to check SSN ( Social Security 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 if the string matched the ReGex ; Driver Code . ; Test Case 1 : ; Test Case 2 : ; Test Case 3 : ; Test Case 4 :
import java . util . regex . * ; class GFG { public static boolean isValidSSN ( String str ) { String regex = " ^ ( ? ! 666 ▁ 000 ▁ 9 \\ d { 2 } ) \\ d { 3 } " + " - ( ? !00 ) \\ d { 2 } - " + " ( ? ! 0 { 4 } ) \\ d { 4 } $ " ; 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 = "856-45-6789" ; ; System . out . println ( isValidSSN ( str1 ) ) ; String str2 = "000-45-6789" ; ; System . out . println ( isValidSSN ( str2 ) ) ; String str3 = "856-452-6789" ; System . out . println ( isValidSSN ( str3 ) ) ; String str4 = "856-45-0000" ; System . out . println ( isValidSSN ( str4 ) ) ; } }