Skip to content

Validating SSN using regular expressions in Java

Validating a Social Security Number (SSN) using regular expressions in Java is a common task when working with user input. A regular expression is a pattern that defines a set of strings, and it can be used to match and validate strings that follow a specific format.

To validate an SSN using regular expressions in Java, we can use the following steps:

  1. Define the regular expression pattern: We can use the regular expression pattern ^\d{3}-\d{2}-\d{4}$ to match SSNs in the format XXX-XX-XXXX, where X represents a digit.
  2. Compile the regular expression pattern: We need to compile the regular expression pattern into a pattern object using the Pattern.compile() method. This method takes the regular expression pattern as a string argument and returns a pattern object.
  3. Match the SSN against the pattern: We can use the Matcher.matches() method to match the SSN against the pattern object. This method returns true if the SSN matches the pattern, and false otherwise.

Here is an example code snippet that demonstrates how to validate an SSN using regular expressions in Java:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SSNValidator {
    public static void main(String[] args) {
        String ssn = "123-45-6789";
        Pattern pattern = Pattern.compile("^(\\d{3}-\\d{2}-\\d{4})$");
        Matcher matcher = pattern.matcher(ssn);
        if (matcher.matches()) {
            System.out.println("Valid SSN");
        } else {
            System.out.println("Invalid SSN");
        }
    }
}


In this example, we define the SSN as a string variable ssn, and we define the regular expression pattern as a string argument to the Pattern.compile() method. We then create a matcher object using the pattern.matcher() method and match the SSN against the pattern using the matcher.matches() method.

If the SSN matches the pattern, we print “Valid SSN”. Otherwise, we print “Invalid SSN”.

See also  Sort a string using Stream API in Java 8

In summary, validating an SSN using regular expressions in Java involves defining a regular expression pattern, compiling the pattern, and matching the SSN against the pattern using a matcher object.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.