0 votes

I have not found a good example of how to write an expression for SSN. I have created one:

[0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][0-9][0-9], but this gets any value. I want to exclude if the first three characters start with '000' or '666' and the range of the first three is not within 800-9999. Do you have an example like this?

by (715 points)

2 Answers

0 votes

The Social Security Number Wikipedia page provides some useful information on restrictions for Valid SSNs.

The following are considered invalid:

  • Numbers with all zeros in any digit group (000-##-####, ###-00-####, ###-##-0000)
  • Numbers with 666 or 900-999 in the first digit group
  • Numbers from 987-65-4320 to 987-65-4329 are reserved for use in advertisements (although this would be excluded by the previous rule)

With those rules in mind this regex should do the trick:

(?!(000|666))[0-8]\d{2}-(?!00)\d{2}-(?!0000)\d{4}
by (29.5k points)
0 votes

Just a small nitpick. Dave's example is superb. I tell myself that I can think in Regular Expression, but I think Dave really can.

This is really a pattern for a potentially valid SSN, and in searching data files this is all one could likely achieve. To truly validate an SSN, one would need to take that matched pattern and then feed it through some sort of validation service.

by (730 points)
...