GSto
GSto

Reputation: 42350

Matching Delimiters With Regular Expressions

I have a situation where I need to validate social security numbers, and they can be input in any of the three following formats:

123-45-6789 123/45/6789 123456789

I tried writing a regular expression to match these, and came up with this:

^[0-9]{3}(-|/)?[0-9]{2}(-|/)?[0-9]{4}$

which is close, but it still allows strings like 123-45/6789 through, which I would like to prevent. Is there any way to match the delimiters such that all hypens are allowed, and all forward slashes are allowed, but not a combination of the two?

Upvotes: 2

Views: 359

Answers (2)

anubhava
anubhava

Reputation: 785286

Better to use this regex:

/^\d{3}(\/|-|)\d{2}\1\d{4}$/

This will not match 123-45/6789 and 123-456789 but
will match 123-45-6789 or 123/45/6789 or 123456789

Upvotes: 4

Gabriel Roth
Gabriel Roth

Reputation: 1040

This should work:

^[0-9]{3}([-|/]?)[0-9]{2}\1[0-9]{4}$

The \1 is a backreference to the subpattern ([-|/]?), so it matches whatever was found for the first delimiter.

Upvotes: 4

Related Questions