Dale
Dale

Reputation: 1301

Looking for a cleaner RegEx solution to matching different formats for a SSN

To see what I want, check out the regex I'm using. I'll try to explain it in English. I want to match 4444 or 444444444 or 444-44-4444. Here's what i have and it does what I want.

^[0-9]{9}$|^[0-9]{4}$|^[0-9]{3}-[0-9]{2}-[0-9]{4}$

Is there a way to do it without the ORs? I thought about doing this

([0-9]{3}-?[0-9]{2}-?)?[0-9]{4}

but that allows 222-222222 which I want to exclude.

Upvotes: 1

Views: 318

Answers (2)

ΩmegaMan
ΩmegaMan

Reputation: 31686

The pattern marked as answer actual fails because it doesn't match the US Spec for valid SSN numbers!

Using the match invalidator this pattern works and throws out 000 and 666 or numbers which start with 9xx as per the government specification Social Security Number Randomization

# To use this regex pattern specify IgnoreWhiteSpace 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!)
(?<FIRST>\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
(?<SECOND>\d\d)             # Match next two digits
(?:[\s-]?)                  # Match but don't capture a possible space or dash
(?<THIRD>\d{4})             # Match the final for digits
$                           # EOL anchor

I describe the use of the match invalidator on my blog article Regular Expression (Regex) Match Invalidator (?!) in .Net.

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816790

You should be able to do this with backreferences:

^(?:\d{3}(-?)\d{2}\1)?\d{4}$

If a - is present, it is captured and can be referenced with \1. If it's not present, \1 will just be empty. So it essentially means: If - is at that position, it must be at the other position too.

DEMO

Upvotes: 1

Related Questions