combining two regex patters making either one optiona

Viewed 48

I am writing a REGEX for social secuirty number. I want to combine the two regex so that social security number can be accepted like so:

123456789
123-45-6789

After searching other post on the internet, I came up with something like so:

 Regex regx = new Regex("^\\d{9}$");
 Regex regx2 = new Regex("^\\d{3}-\\d{2}-\\d{4}$");

Can I combine them together so that if the user enters 12345678 or 123-45-6789. they both will be valid.

any help will be appreciated.

3 Answers

If you can really only admit one or the other SSN version, then I would just combine your two regex patterns using an alternation:

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

Demo

You can combine the regex as pattern bellow, if you wants one or other:

^\\d{3}(\\d{6}|-\\d{2}-\\d{4})$
Related