SSN Regex Python Validator

Search...

⌘K

SSN Regex Python Validator

Search...

⌘K


SSN Regex Python Validator

Validate US Social Security Numbers (SSNs) effortlessly with the SSN Regex Python Validator. This tool ensures the correct “AAA-GG-SSSS” structure using Python’s re module. Also explore Email Regex Python Validator, Phone Number Regex Python Validator, and Python Regex Tester for broader input validation.

bb:aa:dd:aa:55:55
Possible security issues
This regex appears to be safe.
Explanation
  • [A-Z]: uppercase letters
  • [a-z]: lowercase letters
  • [0-9]: digits
  • \.: a literal dot
  • +: one or more of the preceding
  • *: zero or more of the preceding
  • ?: optional (zero or one)
  • ^: start of string
  • $: end of string
Match information
Match: "bb:aa:dd:aa:55:55"
Test your APIs today!

Write in plain English — Qodex turns it into secure, ready-to-run tests.

Regular Expression - Documentation

What is SSN Regex?


A Social Security Number (SSN) in the U.S. follows the standard format:

XXX-XX-XXXX


where:

  • XXX: Area number (3 digits)

  • XX: Group number (2 digits)

  • XXXX: Serial number (4 digits)


This format ensures structured identification for tax and legal purposes. Using regex helps validate whether an input string follows this format strictly.

To be considered a valid SSN, a string must also meet these specific criteria:

  • 9 digits total, separated into three parts by hyphens ().

  • First part (Area Number): 3 digits; cannot be , , or any value between and .

  • Second part (Group Number): 2 digits; must range from to (not ).

  • Third part (Serial Number): 4 digits; must range from to (not ).

These rules help ensure that only properly structured and potentially valid SSNs pass validation, reducing errors and improving data integrity.


SSN Regex Pattern


The typical regex pattern to validate a properly formatted SSN is:

^\d{3}-\d{2}-\d{4}$


Breakdown:

  • ^\d{3} → Three digits at the start

  • - → First hyphen separator

  • \d{2} → Two digits

  • - → Second hyphen

  • \d{4}$ → Four digits at the end


This ensures strict format matching like 123-45-6789.


What Makes an SSN Valid?


It’s not just about the pattern—there are rules beneath the surface:

  • Nine digits total: The SSN must contain exactly nine digits, split by hyphens.

  • Three parts by hyphens: The format is always .

  • Area number restrictions: The first three digits (the area number) should not be , , or any number from to .

  • Group number restrictions: The middle two digits (the group number) must be between and — is not valid.

  • Serial number restrictions: The last four digits (the serial number) should range from to — is not valid.

So, while a regex like checks the format, true SSN validation involves additional logic to ensure the number itself falls within these official boundaries. This helps catch invalid entries such as , , or , which, while matching the basic pattern, are not legitimate SSNs.

By combining regex with these additional checks, you can more confidently determine whether a given string is a valid SSN—not just a well-formatted one.


Python Example Code


import re

def is_valid_ssn(ssn):
    pattern = re.compile(r'^\d{3}-\d{2}-\d{4}$')
    return bool(pattern.fullmatch(ssn))

# Test Cases
print(is_valid_ssn("123-45-6789"))  # True
print(is_valid_ssn("123456789"))    # False
print(is_valid_ssn("12-345-6789"))  # False

Test regex variations with the Python Regex Tester.


Time and Space Complexity


Validating an SSN using a regular expression in Python is highly efficient:

  • Time Complexity: Checking a string against the SSN regex runs in O(N) time, where N is the length of the SSN string. This is because the regex engine scans through each character once to verify the format.

  • Space Complexity: The regex validation uses O(1) auxiliary space since it doesn’t require storing additional data proportional to the input size—just a handful of pattern-matching variables behind the scenes.

In practice, this means SSN validation with regex is both fast and lightweight, making it suitable for everything from web form checks to large database sweeps.


Use Cases


  • User Identity Verification: Ensure accurate SSN input during user registration or onboarding.

  • Data Cleaning: Detect and correct improperly formatted SSNs in databases.

  • Security & Compliance: Verify SSN format before transmitting sensitive data.


You can combine this with:


Regex Metacharacters Used


  • ^ : Anchors the start of the string

  • \d : Matches any digit (0–9)

  • {n} : Matches exactly n digits

  • - : Matches literal hyphens in SSNs

  • $ : Anchors the end of the string


How to Validate SSNs in JavaScript


If you need to confirm US Social Security Numbers on the frontend (or in any JavaScript-powered environment), you can use a regular expression to ensure each input follows the “AAA-GG-SSSS” convention.

Here’s a simple approach using JavaScript’s built-in RegExp:

// Regular expression for strict SSN validation
const ssnPattern = /^(?!6660009\d{2})\d{3}-(?!00)\d{2}-(?!0{4})\d{4}$/;

function isValidSSN(ssn) {
  if (!ssn) return false; // Reject empty inputs
  return ssnPattern.test(ssn);
}

// Example usage:
console.log(isValidSSN("856-45-6789")); // true (valid)
console.log(isValidSSN("000-45-6789")); // false (invalid area)
console.log(isValidSSN("856-452-6789")); // false (incorrect format)
console.log(isValidSSN("856-45-0000")); // false (invalid serial)

What the Regex Does

  • Ensures the area number (first three digits) isn’t 666, 000, or within the 900–999 range.

  • Confirms the group number (middle two digits) isn't 00.

  • Verifies the serial number (last four digits) isn’t all zeros.

  • Forces proper hyphen placement.

This pattern guards against obvious fakes and badly formatted numbers. For more advanced needs, consider combining it with additional verification (such as querying official databases), but for format validation, this approach is solid.

Test JavaScript regexes using your favorite tool—or integrate the logic above into your web forms for real-time validation.


Java Example for SSN Validation


If you need to validate SSNs in a Java application, you can use the Pattern and Matcher classes from Java's standard library. Here’s a simple way to perform strict SSN validation using regex:

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

public class SSNValidator {
    // Regular expression for strict SSN validation
    private static final String SSN_REGEX =
        "^(?!6660009\\d{2})\\d{3}-(?!00)\\d{2}-(?!0{4})\\d{4}$";
    private static final Pattern pattern = Pattern.compile(SSN_REGEX);

    public static boolean isValidSSN(String ssn) {
        if (ssn == null) return false;
        Matcher matcher = pattern.matcher(ssn);
        return matcher.matches();
    }

    public static void main(String[] args) {
        // Example SSNs to test
        System.out.println(isValidSSN("856-45-6789"));   // true
        System.out.println(isValidSSN("000-45-6789"));   // false
        System.out.println(isValidSSN("856-452-6789"));  // false
        System.out.println(isValidSSN("856-45-0000"));   // false
    }
}

Explanation:

  • The regex ensures the SSN does not start with "666", "000", or a number beginning with "9".

  • Group (middle) must not be "00".

  • Serial (last group) must not be "0000".

  • All other digits must match the "XXX-XX-XXXX" structure.

This approach helps catch common invalid SSNs, and you can easily expand the logic for further checks as needed.


C# Example: Validating SSNs


If you’re working with .NET or building apps in C#, you can also harness regular expressions to validate Social Security Numbers. While the approach is similar to Python, C#’s Regex class offers precise control and flexibility.

Here’s a straightforward example of SSN validation logic in C#:

using System;
using System.Text.RegularExpressions;

public class SSNValidator
{
    // Validate US SSN format and value constraints
    public static bool IsValidSSN(string ssn)
    {
        // Regex:
        // - Area numbers (first three digits) can't be 000, 666, or 900-999
        // - Group (middle two digits) can't be 00
        // - Serial (last four digits) can't be 0000
        string pattern = @"^(?!6660009\d{2})\d{3}-(?!00)\d{2}-(?!0000)\d{4}$";
        return Regex.IsMatch(ssn, pattern);
    }

    public static void Main()
    {
        var testSSNs = new[]
        {
            "856-45-6789",   // Valid
            "000-45-6789",   // Invalid area
            "856-452-6789",  // Invalid format
            "856-45-0000"    // Invalid serial
        };

        foreach (var ssn in testSSNs)
        {
            Console.WriteLine($"{ssn}: {IsValidSSN(ssn)}"

How it works:

  • The regular expression checks both the numeric structure and disallows invalid area, group, and serial numbers.

  • The IsValidSSN method returns true for valid SSNs conforming to real-world rules—not just format.

  • Run this code in any C# environment (like Visual Studio, JetBrains Rider, or online C# editors) to validate your inputs.

This follows a similar logic to the Python example above, ensuring both format and validity constraints are enforced for US Social Security Numbers.


C++ Implementation for SSN Validation


Need to validate Social Security Numbers in C++? You can apply a similar pattern-matching technique using the <regex> library. Here’s how you can perform strict SSN format checks, guarding against common invalid entries:

#include 
#include 
#include 

bool is_valid_ssn(const std::string& ssn) {
    // Pattern enforces:
    // - Area number cannot be 000, 666, or in the 900–999 range
    // - Group number cannot be 00
    // - Serial number cannot be 0000
    std::regex pattern(R"(^(?!6660009\d{2})\d{3}-(?!00)\d{2}-(?!0000)\d{4}$)");
    return std::regex_match(ssn, pattern);
}

int main() {
    std::string samples[] = {
        "856-45-6789",  // Valid
        "000-45-6789",  // Invalid (Area)
        "856-452-6789", // Invalid (Group)
        "856-45-0000"   // Invalid (Serial)
    };

    for (const auto& ssn : samples) {
        std::cout << ssn << ": " << (is_valid_ssn(ssn) ? "Valid" : "Invalid") << std::endl;
    }
    return 0;
}

This approach closely mirrors the regex logic used in Python. The regular expression works to block out prohibited values for area, group, and serial numbers per official SSN assignment rules.

  • Area Number (first three digits): Must not be 000, 666, or within the 900–999 range.

  • Group Number (middle two digits): Must not be 00.

  • Serial Number (last four digits): Must not be 0000.

With this C++ snippet, you can quickly integrate SSN validation directly into your application logic.


Pro Tips


  • Always anchor patterns with ^ and $ to avoid partial matches.

  • Preprocess user input to trim whitespaces before validation.

  • You can extend validation to exclude invalid combinations (like 000 or 666) using advanced regex or logic.

  • Avoid storing plain SSNs—encrypt them after validation.

  • Use Python Regex Tester to experiment before deploying.

  • Combine with Date Regex Python Validator if SSNs are part of a larger structured document.


Frequently asked questions

Can this regex validate both hyphenated and non-hyphenated SSNs?×
No, the current pattern (^\d{3}-\d{2}-\d{4}$) strictly matches the hyphenated format. To allow both formats, you’d need to modify the pattern to: ^\d{3}-?\d{2}-?\d{4}$.
Does this regex detect invalid or disallowed SSN combinations like 000 or 666?+
Is this pattern sufficient for use in government or financial systems?+
What if users enter leading/trailing spaces in the SSN?+
Can I use this pattern inside a larger data validation pipeline?+

SSN Regex Python Validator

Search...

⌘K

SSN Regex Python Validator

Search...

⌘K


SSN Regex Python Validator

SSN Regex Python Validator

Validate US Social Security Numbers (SSNs) effortlessly with the SSN Regex Python Validator. This tool ensures the correct “AAA-GG-SSSS” structure using Python’s re module. Also explore Email Regex Python Validator, Phone Number Regex Python Validator, and Python Regex Tester for broader input validation.

bb:aa:dd:aa:55:55
Possible security issues
This regex appears to be safe.
Explanation
  • [A-Z]: uppercase letters
  • [a-z]: lowercase letters
  • [0-9]: digits
  • \.: a literal dot
  • +: one or more of the preceding
  • *: zero or more of the preceding
  • ?: optional (zero or one)
  • ^: start of string
  • $: end of string
Match information
Match: "bb:aa:dd:aa:55:55"
Test your APIs today!

Write in plain English — Qodex turns it into secure, ready-to-run tests.

Regular Expression - Documentation

What is SSN Regex?


A Social Security Number (SSN) in the U.S. follows the standard format:

XXX-XX-XXXX


where:

  • XXX: Area number (3 digits)

  • XX: Group number (2 digits)

  • XXXX: Serial number (4 digits)


This format ensures structured identification for tax and legal purposes. Using regex helps validate whether an input string follows this format strictly.

To be considered a valid SSN, a string must also meet these specific criteria:

  • 9 digits total, separated into three parts by hyphens ().

  • First part (Area Number): 3 digits; cannot be , , or any value between and .

  • Second part (Group Number): 2 digits; must range from to (not ).

  • Third part (Serial Number): 4 digits; must range from to (not ).

These rules help ensure that only properly structured and potentially valid SSNs pass validation, reducing errors and improving data integrity.


SSN Regex Pattern


The typical regex pattern to validate a properly formatted SSN is:

^\d{3}-\d{2}-\d{4}$


Breakdown:

  • ^\d{3} → Three digits at the start

  • - → First hyphen separator

  • \d{2} → Two digits

  • - → Second hyphen

  • \d{4}$ → Four digits at the end


This ensures strict format matching like 123-45-6789.


What Makes an SSN Valid?


It’s not just about the pattern—there are rules beneath the surface:

  • Nine digits total: The SSN must contain exactly nine digits, split by hyphens.

  • Three parts by hyphens: The format is always .

  • Area number restrictions: The first three digits (the area number) should not be , , or any number from to .

  • Group number restrictions: The middle two digits (the group number) must be between and — is not valid.

  • Serial number restrictions: The last four digits (the serial number) should range from to — is not valid.

So, while a regex like checks the format, true SSN validation involves additional logic to ensure the number itself falls within these official boundaries. This helps catch invalid entries such as , , or , which, while matching the basic pattern, are not legitimate SSNs.

By combining regex with these additional checks, you can more confidently determine whether a given string is a valid SSN—not just a well-formatted one.


Python Example Code


import re

def is_valid_ssn(ssn):
    pattern = re.compile(r'^\d{3}-\d{2}-\d{4}$')
    return bool(pattern.fullmatch(ssn))

# Test Cases
print(is_valid_ssn("123-45-6789"))  # True
print(is_valid_ssn("123456789"))    # False
print(is_valid_ssn("12-345-6789"))  # False

Test regex variations with the Python Regex Tester.


Time and Space Complexity


Validating an SSN using a regular expression in Python is highly efficient:

  • Time Complexity: Checking a string against the SSN regex runs in O(N) time, where N is the length of the SSN string. This is because the regex engine scans through each character once to verify the format.

  • Space Complexity: The regex validation uses O(1) auxiliary space since it doesn’t require storing additional data proportional to the input size—just a handful of pattern-matching variables behind the scenes.

In practice, this means SSN validation with regex is both fast and lightweight, making it suitable for everything from web form checks to large database sweeps.


Use Cases


  • User Identity Verification: Ensure accurate SSN input during user registration or onboarding.

  • Data Cleaning: Detect and correct improperly formatted SSNs in databases.

  • Security & Compliance: Verify SSN format before transmitting sensitive data.


You can combine this with:


Regex Metacharacters Used


  • ^ : Anchors the start of the string

  • \d : Matches any digit (0–9)

  • {n} : Matches exactly n digits

  • - : Matches literal hyphens in SSNs

  • $ : Anchors the end of the string


How to Validate SSNs in JavaScript


If you need to confirm US Social Security Numbers on the frontend (or in any JavaScript-powered environment), you can use a regular expression to ensure each input follows the “AAA-GG-SSSS” convention.

Here’s a simple approach using JavaScript’s built-in RegExp:

// Regular expression for strict SSN validation
const ssnPattern = /^(?!6660009\d{2})\d{3}-(?!00)\d{2}-(?!0{4})\d{4}$/;

function isValidSSN(ssn) {
  if (!ssn) return false; // Reject empty inputs
  return ssnPattern.test(ssn);
}

// Example usage:
console.log(isValidSSN("856-45-6789")); // true (valid)
console.log(isValidSSN("000-45-6789")); // false (invalid area)
console.log(isValidSSN("856-452-6789")); // false (incorrect format)
console.log(isValidSSN("856-45-0000")); // false (invalid serial)

What the Regex Does

  • Ensures the area number (first three digits) isn’t 666, 000, or within the 900–999 range.

  • Confirms the group number (middle two digits) isn't 00.

  • Verifies the serial number (last four digits) isn’t all zeros.

  • Forces proper hyphen placement.

This pattern guards against obvious fakes and badly formatted numbers. For more advanced needs, consider combining it with additional verification (such as querying official databases), but for format validation, this approach is solid.

Test JavaScript regexes using your favorite tool—or integrate the logic above into your web forms for real-time validation.


Java Example for SSN Validation


If you need to validate SSNs in a Java application, you can use the Pattern and Matcher classes from Java's standard library. Here’s a simple way to perform strict SSN validation using regex:

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

public class SSNValidator {
    // Regular expression for strict SSN validation
    private static final String SSN_REGEX =
        "^(?!6660009\\d{2})\\d{3}-(?!00)\\d{2}-(?!0{4})\\d{4}$";
    private static final Pattern pattern = Pattern.compile(SSN_REGEX);

    public static boolean isValidSSN(String ssn) {
        if (ssn == null) return false;
        Matcher matcher = pattern.matcher(ssn);
        return matcher.matches();
    }

    public static void main(String[] args) {
        // Example SSNs to test
        System.out.println(isValidSSN("856-45-6789"));   // true
        System.out.println(isValidSSN("000-45-6789"));   // false
        System.out.println(isValidSSN("856-452-6789"));  // false
        System.out.println(isValidSSN("856-45-0000"));   // false
    }
}

Explanation:

  • The regex ensures the SSN does not start with "666", "000", or a number beginning with "9".

  • Group (middle) must not be "00".

  • Serial (last group) must not be "0000".

  • All other digits must match the "XXX-XX-XXXX" structure.

This approach helps catch common invalid SSNs, and you can easily expand the logic for further checks as needed.


C# Example: Validating SSNs


If you’re working with .NET or building apps in C#, you can also harness regular expressions to validate Social Security Numbers. While the approach is similar to Python, C#’s Regex class offers precise control and flexibility.

Here’s a straightforward example of SSN validation logic in C#:

using System;
using System.Text.RegularExpressions;

public class SSNValidator
{
    // Validate US SSN format and value constraints
    public static bool IsValidSSN(string ssn)
    {
        // Regex:
        // - Area numbers (first three digits) can't be 000, 666, or 900-999
        // - Group (middle two digits) can't be 00
        // - Serial (last four digits) can't be 0000
        string pattern = @"^(?!6660009\d{2})\d{3}-(?!00)\d{2}-(?!0000)\d{4}$";
        return Regex.IsMatch(ssn, pattern);
    }

    public static void Main()
    {
        var testSSNs = new[]
        {
            "856-45-6789",   // Valid
            "000-45-6789",   // Invalid area
            "856-452-6789",  // Invalid format
            "856-45-0000"    // Invalid serial
        };

        foreach (var ssn in testSSNs)
        {
            Console.WriteLine($"{ssn}: {IsValidSSN(ssn)}"

How it works:

  • The regular expression checks both the numeric structure and disallows invalid area, group, and serial numbers.

  • The IsValidSSN method returns true for valid SSNs conforming to real-world rules—not just format.

  • Run this code in any C# environment (like Visual Studio, JetBrains Rider, or online C# editors) to validate your inputs.

This follows a similar logic to the Python example above, ensuring both format and validity constraints are enforced for US Social Security Numbers.


C++ Implementation for SSN Validation


Need to validate Social Security Numbers in C++? You can apply a similar pattern-matching technique using the <regex> library. Here’s how you can perform strict SSN format checks, guarding against common invalid entries:

#include 
#include 
#include 

bool is_valid_ssn(const std::string& ssn) {
    // Pattern enforces:
    // - Area number cannot be 000, 666, or in the 900–999 range
    // - Group number cannot be 00
    // - Serial number cannot be 0000
    std::regex pattern(R"(^(?!6660009\d{2})\d{3}-(?!00)\d{2}-(?!0000)\d{4}$)");
    return std::regex_match(ssn, pattern);
}

int main() {
    std::string samples[] = {
        "856-45-6789",  // Valid
        "000-45-6789",  // Invalid (Area)
        "856-452-6789", // Invalid (Group)
        "856-45-0000"   // Invalid (Serial)
    };

    for (const auto& ssn : samples) {
        std::cout << ssn << ": " << (is_valid_ssn(ssn) ? "Valid" : "Invalid") << std::endl;
    }
    return 0;
}

This approach closely mirrors the regex logic used in Python. The regular expression works to block out prohibited values for area, group, and serial numbers per official SSN assignment rules.

  • Area Number (first three digits): Must not be 000, 666, or within the 900–999 range.

  • Group Number (middle two digits): Must not be 00.

  • Serial Number (last four digits): Must not be 0000.

With this C++ snippet, you can quickly integrate SSN validation directly into your application logic.


Pro Tips


  • Always anchor patterns with ^ and $ to avoid partial matches.

  • Preprocess user input to trim whitespaces before validation.

  • You can extend validation to exclude invalid combinations (like 000 or 666) using advanced regex or logic.

  • Avoid storing plain SSNs—encrypt them after validation.

  • Use Python Regex Tester to experiment before deploying.

  • Combine with Date Regex Python Validator if SSNs are part of a larger structured document.


Frequently asked questions

Can this regex validate both hyphenated and non-hyphenated SSNs?×
No, the current pattern (^\d{3}-\d{2}-\d{4}$) strictly matches the hyphenated format. To allow both formats, you’d need to modify the pattern to: ^\d{3}-?\d{2}-?\d{4}$.
Does this regex detect invalid or disallowed SSN combinations like 000 or 666?+
Is this pattern sufficient for use in government or financial systems?+
What if users enter leading/trailing spaces in the SSN?+
Can I use this pattern inside a larger data validation pipeline?+