0

I am trying to validate a Canada Postal Code and I saw several RegEx 1, 2 and many more but none of them works as should be. I am trying with this one:

/[ABCEGHJKLMNPRSTVXY][0-9][ABCEGHJKLMNPRSTVWXYZ] ?[0-9][ABCEGHJKLMNPRSTVWXYZ][0-9]/gmi

Which is not working good as you may see in this test there should only match the first line because postal code needs and it's mandatory 3AllowedChars_emptySpace_3AllowedChars, then having this, how do I restrict only 3 chars before the empty space and 3 after and of course having the valid chars for Canada postal code? Any help?

UPDATE

Based on the solution posted here is the fix:

/^[ABCEGHJKLMNPRSTVXY]\d[A-Za-z][ -]\d[A-Za-z]\d$/gmi

The problem is that ? before [ -] means optional and the empty space is not optional. You can test valid matches here

ReynierPM
  • 17,594
  • 53
  • 193
  • 363

1 Answers1

4

If all you need is a regex for canada postal code, try this:

^[A-Za-z]\d[A-Za-z][ -]?\d[A-Za-z]\d$

It should do exactly what you're looking for

Pabs123
  • 3,385
  • 13
  • 29
  • Almost there, if you try the same string without empty spaces on the middle you will get a match, I tried to fix this but couldn't – ReynierPM Mar 08 '16 at 17:49
  • See [here](https://regex101.com/r/vB9gT5/2): `K1G6C9` shouldn't be matched and it's matching – ReynierPM Mar 08 '16 at 17:57
  • 1
    if you remove the `?` after `[ -]` it will force it to have either a space or dash – Pabs123 Mar 08 '16 at 19:15