Java Regular Expressions - Validate SSN

Check if SSN is Valid Or Not with Java

Regular Expressions are widely-applicable and used to match patterns in text, whether for search, validation or other processing.

A common way to use them is to check whether a number is valid - i.e. follows a pattern. SSNs (Social Security Numbers) follow a particular pattern, and can be tested with Regular Expressions:

public class RegexTutorial {
   public static void main(String[] args) {
        // Looking for a valid SSN. 
        // You can read more about the SSN rules here: https://www.ssa.gov/kc/SSAFactSheet--IssuingSSNs.pdf
        Pattern pattern = Pattern.compile("^(?!000|666)[0-8][0-9]{2}-(?!00)[0-9]{2}-(?!0000)[0-9]{4}$");
        Matcher matcher = pattern.matcher("332-29-8932");
        boolean match = matcher.matches();
        System.out.println(match);
    }
}

This number follows the SSN format:

true

It starts with 3 numbers, a dash, followed by 2 numbers, a dash, and then 4 numbers. Whether this SSN exists or not is a different debate, though.

Last Updated: January 20th, 2023
Was this helpful?
David LandupAuthor

Entrepreneur, Software and Machine Learning Engineer, with a deep fascination towards the application of Computation and Deep Learning in Life Sciences (Bioinformatics, Drug Discovery, Genomics), Neuroscience (Computational Neuroscience), robotics and BCIs.

Great passion for accessible education and promotion of reason, science, humanism, and progress.

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms