Regular Expression Pattern for SSN using the Match Invalidator (?!) in .Net

Updated 1/9/2012 Updated pattern and placed code into syntax highighter block.
Updated 3/9/2014 Updated pattern to US Government specification Social Security Number Randomization.
Updated 7/9/2019 Removed Broken Links

I have answered this question on MSDN quite a few times and decided to blog it for posterity. The use of the Match Invalidator is to invalidate a whole match. One specifies what will make a match fail by using this…let me explain in the case of validating US Social Security Numbers (SSN) numbers. We want the match to fail if the SSN is invalid, but allow for a valid match to mean that the SSN is valid.

Remember that the (?! …) is used to invalidate the whole match. So with SSN numbers is to specify matches that will fail and then specify the match(es) that will succeed and capture the data as needed.

For example if one is getting a SSN there are two obvious failures that should not be matched, any SSN that starts with a 666 or 000. So we look for that condition such as found in red for invalidate then green for the valid match.

# To use this regex pattern specify IgnorePatternWhiteSpace due to these comments.
^                    # Beginning of line anchor      
(?!9)                # Can't be 900- 999                                   
(?!000)              # If it starts with 000 its bad (STOP MATCH!)
(?!666)              # If it starts with 666 its bad (STOP MATCH!)
(?\d{3})             # Match the First three digits and place into First named capture group
(?:[\s\-]?)          # Match but don't capture a possible space or dash
(?\d\d)              # Match next two digits
(?:[\s-]?)           # Match but don't capture a possible space or dash
(?\d{4})             # Match the final for digits
$                    # EOL anchor

Which says if my SSN starts with 000 or 666 or 9xx  it is obviously a bad number and should not to match .


One Comment

  1. Nice Code Snippets!
    Here is a good example which late you how to implement Regular Expressions with .net for U.S. Social Security Numbers.

    Also get complete code for ASP.NET, VB.NET and C#.NET

    Please check:-

    Chetankumar Akarte

Leave a Reply