Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SSN Regex for 123-45-6789 OR XXX-XX-XXXX

Tags:

regex

Can someone provide me a regex for SSN that matches either

123-45-6789

OR

XXX-XX-XXXX

I currently have ^\d{3}-?\d{2}-?\d{4}$ which matches the first expression, but I need to add the second expression to it as an alternative.

Thanks!

like image 895
Chris Conway Avatar asked Nov 03 '10 13:11

Chris Conway


People also ask

How do you match in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).

What is regex number?

The Regex number range include matching 0 to 9, 1 to 9, 0 to 10, 1 to 10, 1 to 12, 1 to 16 and 1-31, 1-32, 0-99, 0-100, 1-100,1-127, 0-255, 0-999, 1-999, 1-1000 and 1-9999.

What is a valid regex?

The Validation (Regex) property helps you define a set of validation options for a given field. In general, this field property is used to perform validation checks (format, length, etc.) on the value that the user enters in a field. If the user enters a value that does not pass these checks, it will throw an error.


2 Answers

To strictly answer you question:

^(123-45-6789|XXX-XX-XXXX)$ 

should work. ;-)

If you read the section "Valid SSNs" on Wikipedia`s SSN article then it becomes clear that a regex for SSN validation is a bit more complicated.

Accordingly a little bit more accurate pure SSN regex would look like this:

^(?!(000|666|9))\d{3}-(?!00)\d{2}-(?!0000)\d{4}$ 
like image 182
splash Avatar answered Oct 08 '22 00:10

splash


(^\d{3}-?\d{2}-?\d{4}$|^XXX-XX-XXXX$) should do it.

---- EDIT ----

As Joel points out you could also do ^(\d{3}-?\d{2}-?\d{4}|XXX-XX-XXXX)$ which is a little neater.

like image 40
Lazarus Avatar answered Oct 07 '22 22:10

Lazarus