cool
cool

Reputation: 143

combining two regex patters making either one optiona

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.

Upvotes: 2

Views: 54

Answers (3)

user3783243
user3783243

Reputation: 5224

You can use ?s to make the -s optional (you can read more about it here, https://www.regular-expressions.info/optional.html). You can then use a backreference for the first -. (-?) creates the backrefernce and \\1 is its usage.

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

https://regex101.com/r/Q0zR5e/2/

Upvotes: 4

AugustoDeveloper
AugustoDeveloper

Reputation: 11

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

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

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522292

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

Upvotes: 3

Related Questions