Regular Expression for SSN [duplicate]
I have a method in C# that says F开发者_高级运维ormatSSN that takes a SSN in a string format and replaces the dashes. I mean I am expecting the SSN to be in XXX-XX-XXXX format. I want to write a regular expression that makes sure that the SSN is in the format I have mentioned.
Can anyone help me construct a regular expression??
^\d{3}-\d{2}-\d{4}$
\d
is a digit, {X}
is repeat the previous element X
times.
As Dmitry pointed out in comments, adding ^
at the beginning and $
at the end will cause the regex to only match if the entire string is a SSN. Without those anchors strings like abc123-45-6789xyz
would also match.
I used the simple expression in the past, but since there are some rules in the formation of SSN, I came up with something a little bit more elaborated:
^(?!000)(?!666)(?!9[0-9][0-9])\d{3}[- ]?(?!00)\d{2}[- ]?(?!0000)\d{4}$
This regex correctly excludes SSNs beginning with 666, 000 and 900-999, according to the Social Security Number Randomization.
You can try it out at Rubular.
You can also try
[RegularExpression(@"^\d{9}|\d{3}-\d{2}-\d{4}$",
ErrorMessage = "Invalid Social Security Number")]
精彩评论