-3

I need a regex which can satisfy both SSN and Tax ID. It can take spaces or even hyphens.

Here are valid formats:

  1. 12-3456789
  2. 123456789
  3. 123 45 6789
  4. 123-45-6789

Can someone help?

2 Answers2

0

You can use something like this: \d{2,3}[- ]?\d{2}[- ]?\d{4,5}

Test it out here: https://regex101.com/r/TJa5fE/2

Chrispresso
  • 3,037
  • 11
  • 24
  • I still don't think this meets OP's requirements, as it allows strings like `12 34-5678`, which wouldn't be valid in OPs spec. – esqew Oct 28 '20 at 23:26
0

My interpretation of the "valid" strings boils down to two distinct patterns which can use either -, a whitespace character, or nothing at all as a separator. This pattern ensures that when a separator is used more than once, it matches across both instances by using the \k{} token:

^\d{2}[-\s]?\d{7}$|\d{3}(?<sep>[-\s])\d{2}\k<sep>\d{4}

Regex101

Be mindful that \k is only supported in select RegExp engines (linked answer is slightly outdated, but still helpful starting point for research). I'll assume you're using a supported engine, as you haven't mentioned specifically what language/engine you're working with.

esqew
  • 34,625
  • 25
  • 85
  • 121
  • Esqew, I was in a rush to test the regex and did not read through your entire answer. I'm using javascript to test this regex and updating regex to escape "\k" breaks pattern for 123-456-7890 and123 456 7890 patterns. Is there an alternative? – aspnetbeginner245 Oct 29 '20 at 02:42
  • @aspnetbeginner245 Did you happen to do any research on your own in order to solve the problem? It's [well documented that JavaScript supports the same `\k` token for backreferences](https://javascript.info/regexp-backreferences). The only difference is that syntactically it's slightly different (`\k` vs. `\k{sep}`); see my updated [Regex101](https://regex101.com/r/EWUHHF/2). – esqew Oct 29 '20 at 02:44