In this java regex tutorial, we will learn to use regular expressions to test whether a user has entered a valid Social Security number in your application or website form.
Valid SSN Number Format
United States Social Security numbers are nine-digit numbers in the format AAA-GG-SSSS with following rules.
- The first three digits called the area number. The area number cannot be 000, 666, or between 900 and 999.
- Digits four and five are called the group number and range from 01 to 99.
- The last four digits are serial numbers from 0001 to 9999.
To validate all above 3 rules, our regex would be:
Regex : ^(?!000|666)[0-8][0-9]{2}-(?!00)[0-9]{2}-(?!0000)[0-9]{4}$
Explanation of Regex of Validate SSN
^ # Assert position at the beginning of the string. (?!000|666) # Assert that neither "000" nor "666" can be matched here. [0-8] # Match a digit between 0 and 8. [0-9]{2} # Match a digit, exactly two times. - # Match a literal "-". (?!00) # Assert that "00" cannot be matched here. [0-9]{2} # Match a digit, exactly two times. - # Match a literal "-". (?!0000) # Assert that "0000" cannot be matched here. [0-9]{4} # Match a digit, exactly four times. $ # Assert position at the end of the string.
Now let’s test our SSN validation regex using some demo SSN numbers.
List<String> ssns = new ArrayList<String>(); //Valid SSNs ssns.add("123-45-6789"); ssns.add("856-45-6789"); //Invalid SSNs ssns.add("000-45-6789"); ssns.add("666-45-6789"); ssns.add("901-45-6789"); ssns.add("85-345-6789"); ssns.add("856-453-6789"); ssns.add("856-45-67891"); ssns.add("856-456789"); String regex = "^(?!000|666)[0-8][0-9]{2}-(?!00)[0-9]{2}-(?!0000)[0-9]{4}$"; Pattern pattern = Pattern.compile(regex); for (String number : ssns) { Matcher matcher = pattern.matcher(number); System.out.println(matcher.matches()); } Output: true true false false false false false false false
I will advise to play with above simple regular expression to try more variation.
Happy Learning !!
Comments