Canadian postal code validation - python - regex -


below code have written canadian postal code validation script. it's supposed read in file:

123 4th street, toronto, ontario, m1a 1a1 12456 pine way, montreal, quebec h9z 9z9 56 winding way, thunder bay, ontario, d56 4a3 34 cliff drive, bishop's falls, newfoundland b7e 4t 

and output whether phone number valid or not. of postal codes returning invalid when postal codes 1, , 2 valid , 3 , 4 invalid.

import re  filename = input("please enter name of file containing input canadian postal code: ") fo = open(filename, "r")  line in open(filename):          regex = '^(?!.*[dfioqu])[a-vxy][0-9][a-z]●?[0-9][a-z][0-9]$'         m = re.match(regex, line)          if m not none:                 print("valid: ", line)         else: print("invalid: ", line)  fo.close  

i not guarantee understand the format, seems work:

\b(?!.{0,7}[dfioqu])[a-vxy]\d[a-z][^-\w\d]\d[a-z]\d\b 

demo

you can fix yours (at least example) change:

(?!.*[dfioqu])[a-vxy][0-9][a-z].?[0-9][a-z][0-9] 

(except accepts hyphen, forbidden)

demo

but in case, explicit pattern may best:

\b[abceghj-nprstvxy]\d[abceghj-nprstv-z]\s\d[abceghj-nprstv-z]\d\b 

which completes 1/4 steps of others.

demo