Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient regex for Canadian postal code function

var regex = /[A-Za-z]\d[A-Za-z] ?\d[A-Za-z]\d/; var match = regex.exec(value); if (match){     if ( (value.indexOf("-") !== -1 || value.indexOf(" ") !== -1 ) && value.length() == 7 ) {         return true;     } else if ( (value.indexOf("-") == -1 || value.indexOf(" ") == -1 ) && value.length() == 6 ) {         return true;     } } else {         return false; } 

The regex looks for the pattern A0A 1B1. true tests:

A0A 1B1

A0A-1B1

A0A1B1

A0A1B1C << problem child

so I added a check for "-" or " " and then a check for length.

Is there a regex, or more efficient method?

like image 352
Jason Avatar asked Apr 02 '13 21:04

Jason


People also ask

What is the format of Canadian postal code?

The postal code is a six-character uniformly structured, alphanumeric code in the form “ANA NAN” where “A” is an alphabetic character and “N” is a numeric character. Two segments make up a postal code: Forward Sortation Area (FSA) and Local Delivery Unit (LDU).

Are postal codes alphanumeric?

Most of the postal code systems are numeric; only a few are alphanumeric (i.e., use both letters and digits). Alphanumeric systems can, given the same number of characters, encode many more locations.


2 Answers

User kind, postal code strict, most efficient format:

/^[ABCEGHJ-NPRSTVXY]\d[ABCEGHJ-NPRSTV-Z][ -]?\d[ABCEGHJ-NPRSTV-Z]\d$/i 

Allows:

  • h2t-1b8
  • h2z 1b8
  • H2Z1B8

Disallows:

  • Z2T 1B8 (leading Z)
  • H2T 1O3 (contains O)

Leading Z,W or to contain D, F, I, O, Q or U

like image 95
Dan Avatar answered Sep 19 '22 06:09

Dan


Add anchors to your pattern:

var regex = /^[A-Za-z]\d[A-Za-z][ -]?\d[A-Za-z]\d$/; 

^ means "start of string" and $ means "end of string". Adding these anchors will prevent the C from slipping in to the match since your pattern will now expect a whole string to consist of 6 (sometimes 7--as a space) characters. This added bonus should now alleviate you of having to subsequently check the string length.

Also, since it appears that you want to allow hyphens, you can slip that into an optional character class that includes the space you were originally using. Be sure to leave the hyphen as either the very first or very last character; otherwise, you will need to escape it (using a leading backslash) to prevent the regex engine from interpreting it as part of a character range (e.g. A-Z).

like image 33
Kenneth K. Avatar answered Sep 21 '22 06:09

Kenneth K.