Home > front end >  Cananda Social Insurance Number Regex
Cananda Social Insurance Number Regex

Time:03-11

At the moment I'm having some issues with my Regex pattern for matching Cananda Social Insurance Numbers. At the moment my current regex looks like this,

"^\\d{3}\\s?\\d{3}\\s?\\d{3}$"

And it's returning results with the following patterns.

111-999-111
111999111
111 999 111

However, my issue arises when I want to include regex patterns for the below patterns as well.

111.999.111
111/999/111

Moving forward, are there any examples I should try to include this? I'll include my following attempts below which I've had no success with. And just a little background, I'm using Terraform to define my Regex pattern if that is of any help. Thanks!

"^(\\d{3}.\\d{3}.\\d{3})|(\\d{9})$"
"^\\d{3} \\d{3} \\d{3}|\\d{9}|\\d{3}.\\d{3}.\\d{3}|\\d{3}-\\d{3}-\\d{3}|\\d{3}/\\d{3}/\\d{3}$"

CodePudding user response:

The following regex pattern will either match a string with 9 digits, or 3 groups of 3 digits seperated by one delimiter (space, dot, slash, dash)

^\d{3}(?:\d{6}|([ .\/-])\d{3}\1\d{3})$

^ : start of line or string
\d{3} : 3 digits
(?: : start of non-capturing group
\d{6} : 6 digits
| : or
([ .\/-]) : capture group 1 for delimiter
\d{3}\1\d{3} : 3 digits & reference to group 1 & 3 digits
) : end of non-capturing group
$ : end of line or string

Test on regex101 here

CodePudding user response:

This pattern allow a space, dot, hyphen or slash between 3 groups of 3 numbers.

/^(\d{3}[\. \/-]?){2}\d{3}$/gm

Is that what you are looking for?
It matches all your strings.
The weakness is that we can mix the seperators. For example 123.456/789 is allowed.
We can block that, but it needs a longer pattern, for example:

/\b((\d{3} ){2}|(\d{3}-){2}|(\d{3}\.){2}|(\d{3}\/){2}|\d{6})\d{3}\b/gm
  • Related