SSN regex C#

SSN

SSN stands for social security number and is issued to US citizens, permanent and temporary residents.

SSN regex

This number has the following rules:

  • consists of 9 digits and usually divided by 3 parts by hyphen (XXX-XX-XXXX).
  • The first part can not be 000, 666, or between 900-900.
  • Second part can not be 00
  • Third part can not be 0000

Below is a simple SSN regular expression that is divided by hyphens.

  • If you want to make hyphens optional, put ? after each dash
  • If you want to validate SSN without hyphens - just remove them
new Regex("^(?!666|000|9\\d{2})\\d{3}-(?!00)\\d{2}-(?!0{4})\\d{4}$")

Test it!
/^(?!666|000|9\d{2})\d{3}-(?!00)\d{2}-(?!0{4})\d{4}$/

True

False

Enter a text in the input above to see the result

Example code in C#:

using System.Text.RegularExpressions;
using System.Linq;
using System;
                    
public class Program
{
    public static void Main()
    {
        // Validate SSN
        Regex validateSSNRegex = new Regex("^(?!666|000|9\\d{2})\\d{3}-(?!00)\\d{2}-(?!0{4})\\d{4}$");
        Console.WriteLine(validateSSNRegex.IsMatch("100-22-3333"));  // prints True
        
        // Extract SSNs from a string
        Regex extractSSNRegex = new Regex("(?!666|000|9\\d{2})\\d{3}-(?!00)\\d{2}-(?!0{4})\\d{4}");
        string [] extracted = extractSSNRegex.Matches("My SSN is 100-22-3333")
            .Cast()
            .Select(m => m.Value) 
            .ToArray(); 
        Console.WriteLine(String.Join(",", extracted)); // prints 100-22-3333
    }
}
Test it!

True

False

Enter a text in the input above to see the result

Test it!

True

False

Enter a text in the input above to see the result