Skip to content
Related Articles

Related Articles

How to validate SSN (Social Security Number) using Regular Expression
  • Last Updated : 27 Jan, 2021

Given string str, the task is to check whether the given string is valid SSN (Social Security Number) or not by using Regular Expression
The valid SSN (Social Security Number) must satisfy the following conditions: 

  1. It should have 9 digits.
  2. It should be divided into 3 parts by hyphen (-).
  3. The first part should have 3 digits and should not be 000, 666, or between 900 and 999.
  4. The second part should have 2 digits and it should be from 01 to 99.
  5. The third part should have 4 digits and it should be from 0001 to 9999.

Examples: 

Input: str = “856-45-6789”; 
Output: true 
Explanation: The given string satisfies all the above mentioned conditions. Therefore, it is a valid SSN (Social Security Number).

Input: str = “000-45-6789”; 
Output: false 
Explanation: The given string starts with 000. Therefore, it is not a valid SSN (Social Security Number).

Input: str = “856-452-6789”; 
Output: false 
Explanation: The second part of this string has 3 digits. Therefore, it is not a valid SSN (Social Security Number).



Input: str = “856-45-0000”; 
Output: false 
Explanation: The third part of this string is 0000. Therefore, it is not a valid SSN (Social Security Number). 

Approach: The idea is to use Regular Expression to solve this problem. The following steps can be followed to compute the answer. 

  • Get the String.
  • Create a regular expression to check valid SSN (Social Security Number) as mentioned below:
regex = "^(?!666|000|9\\d{2})\\d{3}-(?!00)\\d{2}-(?!0{4})\\d{4}$";
  • Where: 
    • ^ represents the starting of the string.
    • (?!666|000|9\\d{2})\\d{3} represents the first 3 digits should not start with 000, 666, or between 900 and 999.
    • represents the string followed by a hyphen (-).
    • (?!00)\\d{2} represents the next 2 digits should not start with 00 and it should be any from 01-99.
    • represents the string followed by a hyphen (-).
    • (?!0{4})\\d{4} represents the next 4 digits can’t 0000 and it should be any from 0001-9999.
    • $ represents the ending of the string.
  • Match the given string with the regular expression. In Java, this can be done by using Pattern.matcher().
  • Return true if the string matches with the given regular expression, else return false.

Below is the implementation of the above approach:

Java




// Java program to check valid
// SSN (Social Security Number) using
// regex.
import java.util.regex.*;
class GFG {
 
    // Function to validate
    // SSN (Social Security Number).
    public static boolean isValidSSN(String str)
    {
        // Regex to check SSN
        // (Social Security Number).
        String regex = "^(?!666|000|9\\d{2})\\d{3}"
                       + "-(?!00)\\d{2}-"
                       +"(?!0{4})\\d{4}$";
 
        // Compile the ReGex
        Pattern p = Pattern.compile(regex);
 
        // If the string is empty
        // return false
        if (str == null)
        {
            return false;
        }
 
        // Pattern class contains matcher()
        //  method to find matching between
        //  given string and regular expression.
        Matcher m = p.matcher(str);
 
        // Return if the string
        // matched the ReGex
        return m.matches();
    }
 
    // Driver Code.
    public static void main(String args[])
    {
 
        // Test Case 1:
        String str1 = "856-45-6789";
        ;
        System.out.println(isValidSSN(str1));
 
        // Test Case 2:
        String str2 = "000-45-6789";
        ;
        System.out.println(isValidSSN(str2));
 
        // Test Case 3:
        String str3 = "856-452-6789";
        System.out.println(isValidSSN(str3));
 
        // Test Case 4:
        String str4 = "856-45-0000";
        System.out.println(isValidSSN(str4));
    }
}

Python3




# Python3 program to validate
# SSN (Social Security Number)
# using regular expression
import re
 
# Function to validate SSN
# (Social Security Number).
 
 
def isValidSSN(str):
 
    # Regex to check valid
    # SSN (Social Security Number).
    regex = "^(?!666|000|9\\d{2})\\d{3}-(?!00)\\d{2}-(?!0{4})\\d{4}$"
 
    # Compile the ReGex
    p = re.compile(regex)
 
    # If the string is empty
    # return false
    if (str == None):
        return False
 
    # Return if the string
    # matched the ReGex
    if(re.search(p, str)):
        return True
    else:
        return False
 
# Driver code
 
 
# Test Case 1:
str1 = "856-45-6789"
print(isValidSSN(str1))
 
# Test Case 2:
str2 = "000-45-6789"
print(isValidSSN(str2))
 
# Test Case 3:
str3 = "856-452-6789"
print(isValidSSN(str3))
 
# Test Case 4:
str4 = "856-45-0000"
print(isValidSSN(str4))
 
# This code is contributed by avanitrachhadiya2155

C++




// C++ program to validate the
// SSN (Social Security Number)
// using Regular Expression
#include <iostream>
#include <regex>
using namespace std;
 
// Function to validate the SSN
// (Social Security Number)
bool isValidSSN(string str)
{
 
    // Regex to check valid SSN
    // (Social Security Number)
    const regex pattern("^(?!666|000|9\\d{2})"
                        "\\d{3}-(?!00)"
                        "\\d{2}-(?!0{4})\\d{4}$");
 
    // If the SSN (Social Security Number)
    // is empty return false
    if (str.empty())
    {
        return false;
    }
 
    // Return true if the SSN
    // (Social Security Number)
    // matched the ReGex
    if (regex_match(str, pattern))
    {
        return true;
    }
    else {
        return false;
    }
}
 
// Driver Code
int main()
{
    // Test Case 1:
    string str1 = "856-45-6789";
    cout << isValidSSN(str1) << endl;
 
    // Test Case 2:
    string str2 = "000-45-6789";
    cout << isValidSSN(str2) << endl;
 
    // Test Case 3:
    string str3 = "856-452-6789";
    cout << isValidSSN(str3) << endl;
 
    // Test Case 4:
    string str4 = "856-45-0000";
    cout << isValidSSN(str4) << endl;
 
    return 0;
}
 
// This code is contributed by yuvraj_chandra
Output
true
false
false
false

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :