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.

   1: ^                 # To use this regex specify IgnoreWhiteSpace
   2:                   # or remove comments and combine.
   3: (?!000)           # If it starts with 000 its bad
   4: (?!666)           # If it starts with 666 its bad
   5: (?<FIRST>[0-6]\d{2}|7[0-7][0-2])
   6: (?:[ -]?)
   7: (?!00)            # If an invalidate is found *at this point* it invalidates the whole match!
   8: (?<SECOND>\d{2})
   9: (?:[ -]?)
  10: (?![0]{4})
  11: (?<THIRD>\d{4})$

Which says if my SSN starts with 000 or 666 it is obviously a bad item and not to match it or if 00 is found in the middle position…then it should fail the match.

For more examples see these posts on MSDN Regex forum: Help on Regex and Help Building a Regex.

  • Share/Bookmark