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.

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 .

For more examples see these posts on MSDN Regex forum:

Help on Regex
Help Building a Regex.

Share