Java Regular Expressions - Validate SSN

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:
        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();

This number follows the SSN format:


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.

Make Clarity from Data - Quickly Learn Data Visualization with Python

Learn the landscape of Data Visualization tools in Python - work with Seaborn, Plotly, and Bokeh, and excel in Matplotlib!

From simple plot types to ridge plots, surface plots and spectrograms - understand your data and learn to draw conclusions from it.

© 2013-2024 Stack Abuse. All rights reserved.